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 |
---|---|
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:
<
or is it <=
)The following sections explore each of these loops in detail.