C# do-while loop

The do-while is an iteration statement which executes a code block until the condition remains true. A do-while code block must be enclosed in two curly braces {} if loop body has more than one line of code.

Following is the syntax of a do-while statement.

do 
{
   statement(s);
} while( condition );

Let's understand the do-while flow with an image.

As the conditional expression of do-while loop comes after the loop body, the do-while loop gets executed at least once.

Let's understand this with an example.

Example

Try It
using System;
 
namespace TutorialsLeader
{
    public class MyFirstClass
    {
        static void Main()
        {
            int x = 0;
            do
            {
                Console.WriteLine("The value of x is = {0}", x);
                x++;
            } while (x < 10);
        }
    }
}

The above loop prints the value of x from 0-9.

Output

The value of x is = 0
The value of x is = 1
The value of x is = 2
The value of x is = 3
The value of x is = 4
The value of x is = 5
The value of x is = 6
The value of x is = 7
The value of x is = 8
The value of x is = 9

Let's learn about the while loop in the next section.