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
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);
0 Comments