C# While & Do-While Loops
A while loop repeats a block of code as long as its condition remains true. The condition is checked before each iteration, so the loop body might never run if the condition starts false.
A do-while loop is similar, but it checks the condition after running the loop body, guaranteeing the code runs at least once.
while (condition) {
// code
}
do {
// code
} while (condition);while loop
A while loop checks its condition before each pass. If the condition is false from the start, the loop body never executes.
do-while loop
A do-while loop executes the body first, then checks the condition. This guarantees at least one execution, useful for things like input validation menus.
using System;
class Program {
static void Main() {
int i = 0;
while (i < 3) {
Console.WriteLine(i);
i++;
}
}
}0
1
2The loop prints i and increments it until the condition i < 3 becomes false.
using System;
class Program {
static void Main() {
int i = 5;
do {
Console.WriteLine(i);
i++;
} while (i < 3);
}
}5The do-while runs the body once (printing 5) before checking the false condition.
Key points
- while checks the condition before each iteration.
- do-while checks the condition after each iteration, so it runs at least once.
- Loops need a way to eventually make the condition false to avoid infinite loops.
- The increment/decrement operators (++/--) are commonly used with loops.
