C# Do while loop

C# Do while loop is quite similar to the while loop except for one thing. In the do while loop, the statements inside it execute once, and then it checks the condition. So do while guarantees to execute the statements of the iteration 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 the C# do while loop to read the value of integer n from the 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

Do While Example 1

Here, the 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 condition 2 <= 5, which returns true. Again the iteration repeats by printing the n value, i.e., 3

3++, which is 4.

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

..

Until the n value is 5, it will repeat. When n = 5, the 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, the 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 iteration by printing six as output.

Categories C#