< previous page page_475 next page >

Page 475
Guidelines for Choosing a Looping Statement
Here are some guidelines to help you decide when to use each of the three looping statements (While, Do-While, and For).
1. If the loop is a simple count-controlled loop, the For statement is a natural. Concentrating the three loop control actionsinitialize, test, and increment/decrementinto one location (the heading of the For statement) reduces the chances of forgetting to include one of them.
2. If the loop is an event-controlled loop whose body is always executed at least once, a Do-While statement is appropriate.
3. If the loop is an event-controlled loop and nothing is known about the first execution, use a While or a For statement.
4. When in doubt, use a While statement.
5. An infinite loop with break statements sometimes clarifies the code but more often reflects an undisciplined loop design. Use it only after careful consideration of While, Do-While, and For.
Loop Invariants as Program Comments
We've been writing preconditions and postconditions as comments at the beginning of our functions. These assertions help to document the interface between the function and the calling code. From here on, we also include loop invariants as comments in our loops. These assertions help to document important facts about the state of the program while the loop is executing.
Recall from Chapter 6 that a loop invariant is an assertion that must be true each time the loop iterates and when the loop exits. For a loop to be correct, the logical AND of the loop invariant and the loop termination condition must imply that the loop postcondition is true.
We said that the invariant must be true each time the loop iterates. Let's be more specific. When we place a comment with an assertion somewhere in a program, the assertion should be true when control reaches that precise location. We place a loop invariant at some point in the loop, claiming that it is true with respect to that point in the loop. The most useful location for a loop invariant is immediately before the loop test because at this point an iteration has just completed. Here is an example that uses a Do-While loop to sum the integers 1 through 10. To help explain the loop invariant, we also include a loop postcondition.
sum = 0;
count = 1;
do
{

 
< previous page page_475 next page >