Do While Loop in C#

In a do-while loop, the condition is indeed checked after the code block has been executed. This ensures that the code block is executed at least once, even if the condition is initially false.

Do While loop always executes the code and then checks the condition.

Syntax

do
{
    // Code to execute
} while (condition);

Steps

  1. The code block is executed first.
  2. Then, the condition is evaluated.
  3. If the condition is true, the loop continues to execute.
  4. If the condition is false, the loop terminates.

Example

int i = 0;
do
{
    Console.WriteLine(i);
    i++;
} while (i <= 5);

Explanation

int i = 0;

This line initializes a variable i with the value 0. This variable will be used as a counter to control the loop.

do
{
    Console.WriteLine(i);
    i++;
} while (i <= 5);

The code block within the curly braces {} is executed first, which includes printing the current value of i and then incrementing i by 1.

After the code block executes, the condition (i <= 5) is evaluated. If i is less than or equal to 5, the loop continues; otherwise, it terminates.

This loop will print the numbers from 0 to 5 (inclusive) because it starts with i = 0, prints i, and then increments i by 1. It repeats this process until i becomes 6, at which point the condition (i <= 5) becomes false, and the loop terminates.

Result

Output

The do-while loop in C# is useful when the block of code must execute at least once. It's beneficial in scenarios where the initial execution of the loop doesn't depend on the condition being true. Always ensure the loop's exit condition will be met to avoid infinite loops.

If you have any doubts or need further clarification on the do-while loop in C#, please leave a comment, and I'll be happy to assist..!


Similar Articles