C++ While Loop
A `while` loop repeats a block of code as long as its condition remains true, checking the condition before each iteration. A `do...while` loop is similar but always runs the body at least once, checking the condition afterward.
Both loops require the condition to eventually become false, otherwise you get an infinite loop that never terminates.
while loop
`while (condition) { ... }` checks the condition first; if it's false immediately, the body never executes at all.
do...while loop
`do { ... } while (condition);` runs the body once before checking, guaranteeing at least one execution โ useful for menu prompts.
int i = 0;
while (i < 3) {
std::cout << i;
i++;
}012The loop runs while i is less than 3.
int i = 5;
do {
std::cout << i;
} while (i < 3);5do...while runs once even though the condition is already false.
Key points
- while checks the condition before each iteration.
- do...while checks after, guaranteeing at least one run.
- Loop variables must change to avoid infinite loops.
- Both loops need a boolean condition.
