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#:

} 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)
                a++; //increment
            } while (a <= 10); //condition

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.



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.