3.5. Looping Overview

Loops help programmers solve problems that require repetition or iteration. They are instrumental when the number of task repetitions is unknown before the program runs or too great for practical implementation with sequential statements. C++ provides three kinds of loops.

Loop Classification Test Location
for and for-range Determinate loop Test at the top loop
while Indeterminate loop Test at the top loop
do-while Indeterminate loop Test at the bottom loop
Test At The Top Test At The Bottom
A picture showing program control entering the loop-test. The test has true and false exit paths. The false path leaves the loop, while the true path leads to the test body. An arrow leads from the body back to the loop test. A picture showing program control entering the loop body and a path from the body to the loop-test. True and false paths leave the test. The false path leaves the loop, and the true path returns to the loop body.
C++ loop overview. The difference between determinate and indeterminate loops is subtle, blurring their distinction. The number of iterations of a determinate loop is fixed or "known" before the loop begins running, while more dynamic conditions govern indeterminate loop iterations. All C++ loops can operate as determinate or indeterminate loops, so it's convenient to think of for- and for-range loops as "counting" loops and the others as "while some condition is true."

For- and while-loops evaluate the loop-test (a Boolean-valued expression) at the loop's top, making them test at the top loops. Programs run the loop body while the test is true and end when it becomes false. This behavior means that programs can skip the loop body if the test is false when the program first enters the loop. Do-while-loops evaluate the loop-test at the bottom, making them test at the bottom loops. They run while the test is true, stopping when it becomes false. Program execution must "pass-through" the loop's body to reach the loop test, suggesting that programs always run a do-while loop's body at least once.

Since for- and while-loops evaluate the loop test at the top, it's relatively easy for programmers to convert one loop to the other. Do-while loops are the only test at the bottom loop, making it more difficult to interchange them with the other loops.

There are three essential parts of loops that you must look at carefully when trying to understand their behavior:

  1. Pay attention to where the loop begins and ends.
  2. The test driving the loop (e.g., is it < or is it <= )
  3. Where the test occurs (at the top or bottom of the loop). For- and while-loops perform their tests at the top, which means that if the test is initially false, the program skips the statements in the loop's body. Do-while loops test at the bottom after the loop body executes at least once.

The following sections explore each of these loops in detail.