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

} 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());
            } while (n <= 5);

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 iteration 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, it 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 iteration by printing six as output.