C# Do while loop

C# Do while loop is quite similar to the while loop except for one thing. In do while loop, the statements inside the loop execute once, and then it checks the condition. So do while guarantees to execute the statements of the loop at least once.

The syntax of the C# Do while loop is

do
{
   statements;
} while<boolean expression>

C# Do while loop Example

Let us see an example code using do while loop to read the value of integer n from user and print integers until n <= 5 returns true.

using System;

namespace CSharp_Tutorial
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter an integer {0}", " ");
            int n = int.Parse(Console.ReadLine());
            Console.WriteLine();
            do
            {
                Console.WriteLine(n);
                n++;
            } while (n <= 5);
            Console.ReadLine();
        }
    }
}

First output: input is 2

C# Do While Loop 1

Here, control asks the user to enter some integer, and the input has given 2.

Now it prints the integer 2.

2++, which is 3

It will check the condition 2 <= 5, which returns true. Again the loop repeats by printing the n value, i.e., 3

3++, which is 4.

It will check the condition 3 <= 5, which returns true….

..

Until n value is 5, the loop will repeat. When n = 5, control prints the value five and then increments

5++ = 6

Now the condition 6 <= 5 returns false. So the C# control comes out of the loop

Second output: input is 6

C# Do While Loop 2

Here, in this case, as usual, control reads the input six and enters the do loop.

The compiler prints the value 6 and increments, i.e., 6++ = 7.

Now it checks for condition 7 <= 5, which returns false. So it quits the loop by printing six as output.