C++ ยท Chapter 17 of 49

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.

Example 1 (cpp)
int i = 0;
while (i < 3) {
    std::cout << i;
    i++;
}
Output
012

The loop runs while i is less than 3.

Example 2 (cpp)
int i = 5;
do {
    std::cout << i;
} while (i < 3);
Output
5

do...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.
๐Ÿ’ก Note: An infinite loop like `while(true)` is valid and common โ€” pair it with a break statement inside.

๐Ÿ“ Quick Quiz

1. Which loop guarantees at least one execution?

2. A while loop checks its condition:

3. What causes an infinite loop?