The C# do while loop is another way of making your code repeat its execution. It is almost similar the while loop with one minor difference, it checks the condition after the code body has been executed. Let’s look at the syntax of the do while loop.

do
{
   code to repeat;

} while (condition);

As you can see, the condition is at the end of the structure. That means that the code inside the body will be executed at least once. Unlike the while  loop where the body will not execute if the condition is already false the very  first time. One example where you would prefer using a do while loop over the while loop is when getting information from the user. It requires the prompt to show for at least 1 time.

//while version
Console.WriteLine("Enter a number greater than 10: ");
number = Convert.ToInt32(Console.ReadLine());
 
while(number < 10)
{
   Console.WriteLine("Enter a number greater than 10: ");
   number = Convert.ToInt32(Console.ReadLine());
}

Example 1 – Using a while Loop

//do while version
do
{
   Console.WriteLine("Enter a number greater than 10: ");
   number = Convert.ToInt32(Console.ReadLine());  
} while (number < 10);

Example 2 – Using a C# do while Loop

You can see that you have saved a few lines of code by using do while instead of the while loop. Take note that everything you can do with the while loop, you can also do using do while and vice versa.