C# - do while Loop
The do-while loop is the same as the while loop except that in the do-while loop, the code block will be executed at least once.
Syntax:
do { //code block } while(boolean expression);
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 exits when a boolean expression returns false.
Example: do-while Loop
int i = 0;
do
{
Console.WriteLine("Value of i: {0}", i);
i++;
} while (i < 10);
Output:
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
Just as in the case of the for and while loops, you can break out of the do-while loop using the break keyword.
Example: Break do-while Loop
int i = 0;
do
{
Console.WriteLine("Value of i: {0}", i);
i++;
if (i > 5)
break;
} while (true);
Output:
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Nested do-while
The do-while loop can be used inside another do-while loop.
Example: Nested do-while Loop
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:
Value of i: 0
Value of j: 0
Value of j: 1
Value of i: 1
Value of j: 1