do while Loop in C# programming

Do While Loop is just like any other loop in C#, but in this loop we have condition at the end of the loop. So this guarantees the execution of statements inside the loop at least once and the loop will be repeated if the condition is satisfied until the condition is false. The condition can be changed in the loop statements. We can also exit the loop using break statement.

Syntax for Do While Loop in C#:

do
{
    statements;
} while (condition);

Do While Loop starts with a do statement which is followed by statements to be executed in the loop. It ends with a while statement which contains a condition.

Flow chart for Do While Loop:

C# do while loop flowchart

Example 1: C# program for do while loop

C# program to print even natural numbers from 1 to 10.

using System;
namespace loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1; //initialization
            do //start of loop
            {
                if (a % 2 == 0)
                Console.WriteLine(a);
                a++; //increment
            } while (a <= 10); //condition
            Console.ReadLine();
        }
    }
}

In this program, a variable is initialized before the loop starts. When the loop starts it executes the statement in there and increments the value of a at the end of the loop. When the loop is exited, condition is checked and the loop runs again if the condition is still true.

Output:

2
4
6
8
10

Additional Information on do while Loop:

We must be very careful while using this loop. Most of the error in this loop is caused my human errors because the fact that this loop will executes loop statements before checking the condition will confuse us. Further more, it executes the statement at least once.