C# do-while:
The do-while loop is the same as a 'while' loop except that the block of code will be executed at least once, because it first executes the block of code and then it checks the condition.
Syntax:
do
{
//execute code block
} while(boolean expression);
As per the syntax above, do-while loop starts with the 'do' keyword followed by a code block and boolean expression with 'while'.
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 inside do-while
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 loop:
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
Points to Remember :
- The do-while loop executes the block of code repeatedly.
- The do-while loop execute the code atleast once. It includes the conditional expression after the code block and the increment/decrement step should be inside the loop.
- Use the break keyword to stop the execution and exit from a do-while loop.
- An nested do-while loop is allowed.