English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# do...while Loop

The do...while loop is the same as the while loop, but the do...while loop executes the code block at least once.

Syntax:

do
{
    //Code block
} while(condition);

The do...while loop starts with the do keyword, followed by a code block and a boolean expression with the while keyword. The do while loop stops executing when the calculation result of the boolean condition is false. Because while(condition) is specified at the end of the block, it is guaranteed to execute the code block at least once.

int i = 0;
do
{
    Console.WriteLine("i = {0}", i);
    i++;
} while (i < 5);
Output:
i = 0 
i = 1 
i = 2 
i = 3 
i = 4

Specify initialization outside the loop, and specify increment inside the do...while loop/Decrement the counter.

Use break or return to exit the do while loop.

int i = 0;
do
{
    Console.WriteLine("i = {0}", i);
    i++;
    
    if (i > 5)
        break;
} while (i < 10);
Output:
i = 0 
i = 1 
i = 2 
i = 3 
i = 4 
i = 5

Nested do ...while loop

do-while loop can be used within another do-while loop used inside.

int i = 0;
do
{
    Console.WriteLine("Value of i: {0}", i);
    int j = i;
    i++;
                
    do
    {
        Console.WriteLine("Value of j: {0}", j);
        j++;
    } while (j < 2);
} while (i < 2);

Output:

i = 0 
j = 0 
j = 1 
i = 1 
j = 1