C# do...while Loop

In C#, the do...while loop is a type of loop statement that executes a block of code repeatedly while a specified condition remains true, and it tests the condition at the end of each iteration. The syntax of the do...while loop is as follows:

do
{
    // Code to execute at least once
    // Code to execute while the condition is true
} while (condition);
‮S‬ource:www.theitroad.com

The do keyword is followed by the code to be executed, and the while keyword is followed by the condition to test. The code block will always execute at least once, regardless of whether the condition is true or false. If the condition is true, the code inside the loop will be executed again. This will continue until the condition becomes false.

Here is an example that uses a do...while loop to print the numbers from 1 to 10:

int i = 1;
do
{
    Console.WriteLine(i);
    i++;
} while (i <= 10);

In this example, the loop starts with the value of i being 1. The do keyword is followed by the code block that prints out the value of i and increments i by 1. The while keyword is followed by the condition to test whether i is less than or equal to 10. Since i starts at 1, the loop executes the code block once, printing out 1. It then checks the condition and continues executing the code block until i reaches 11.

Like the while loop, it's important to make sure that the condition inside the do...while loop will eventually become false, otherwise the loop will run indefinitely, which is called an infinite loop. To prevent this, you can use a counter variable or a sentinel value to control the loop's execution.