0
0
CsharpHow-ToBeginner · 3 min read

How to Use Do While Loop in C# - Simple Guide

In C#, a do while loop executes the code block once before checking the condition at the end of the loop. It repeats the block as long as the while condition is true, ensuring the code runs at least once.
📐

Syntax

The do while loop syntax in C# consists of the do keyword followed by a block of code inside braces, and then the while keyword with a condition in parentheses ending with a semicolon.

  • do: Starts the loop block.
  • code block: The statements to run at least once.
  • while (condition);: Checks the condition after running the block; if true, repeats the loop.
csharp
do
{
    // code to execute
} while (condition);
💻

Example

This example shows a do while loop that prints numbers from 1 to 5. It runs the print statement first, then checks if the number is less than or equal to 5 to continue.

csharp
using System;

class Program
{
    static void Main()
    {
        int number = 1;
        do
        {
            Console.WriteLine(number);
            number++;
        } while (number <= 5);
    }
}
Output
1 2 3 4 5
⚠️

Common Pitfalls

Common mistakes when using do while loops include:

  • Forgetting the semicolon ; after the while condition.
  • Using a condition that never becomes false, causing an infinite loop.
  • Assuming the loop might not run; do while always runs at least once.
csharp
/* Wrong: Missing semicolon after while condition */
do
{
    Console.WriteLine("Hello");
} while (false)  // <-- missing semicolon here

/* Right: Semicolon included */
do
{
    Console.WriteLine("Hello");
} while (false);
📊

Quick Reference

Remember these tips when using do while loops:

  • The loop runs the code block first, then checks the condition.
  • Use it when you want the code to run at least once.
  • Always end the while condition with a semicolon.

Key Takeaways

A do while loop runs its code block at least once before checking the condition.
Always include a semicolon after the while(condition) statement.
Use do while loops when you need the code to execute before condition checking.
Be careful to avoid infinite loops by ensuring the condition eventually becomes false.
The syntax is simple: do { code } while (condition);