C# Do-While Loop
Syntax
The syntax for a do-while loop in C# is as follows:
do {
// code block to be executed
} while(condition);
Example
int i = 0;
do {
Console.WriteLine(i);
i++;
} while(i < 5);
Output
The output of the above example would be:
0
1
2
3
4
Explanation
A do-while loop is similar to a while loop, but with one key difference - the code block is executed at least once, regardless of the condition. The condition is then checked at the end of the loop, and if it is still true, the loop will execute again.
In the above example, the integer variable i
is set to 0. The code block within the do-while loop will execute, writing the value of i
to the console and then incrementing it by 1. This will continue until i
is no longer less than 5.
Use
A do-while loop can be useful in situations where you want to ensure a block of code is executed at least once, even if the condition is not initially true.
Important Points
- A do-while loop is similar to a while loop, but the code block is executed at least once.
- The condition is checked at the end of the loop, rather than at the beginning like in a while loop.
- A do-while loop is useful when you want to ensure a block of code is executed at least once.
Summary
A do-while loop in C# is a useful tool for ensuring a block of code is executed at least once. The syntax is similar to a while loop, but with the addition of the do
keyword and the condition check at the end of the loop.