C# Do While loop

The do-while loop in C# is a control flow statement that executes a block of code at least once and then repeats the loop as long as a specified condition evaluates to true. It is similar to the while loop, but the key difference is that the condition is evaluated after the execution of the loop body, not before. Therefore, the body of the loop is guaranteed to execute at least once, even if the condition is initially false.

Syntax:


do
{
    // Code to be executed
} while (condition);

Explanation:

condition: This is a boolean expression that will be evaluated after each iteration of the loop. If the condition is true, the loop will continue. If the condition is false, the loop will terminate.

Note:

  1. The body of the loop is executed at least once regardless of the condition, because the condition is checked after the first iteration.
  2. If the condition is true, the loop continues to execute; if false, the loop ends.

Example:


using System;

class ProgramExample
{
    static void Main()
    {
        int count = 1;
        // do-while loop
        do
        {
            Console.WriteLine("number: " + count);
            count++;  // Increment the counter
        }
        while (count <= 5);
    }
}

Output:

number: 1
number: 2
number: 3
number: 4
number: 5

Example: If we define count > 5 in the while loop then it will execute only one time.


using System;

class ProgramExample
{
    static void Main()
    {
        int count = 1;
        
        // do-while loop
        do
        {
            Console.WriteLine("number: " + count);
            count++;  // Increment the counter
        }
        while (count > 5);
    }
}

Output:

number: 1