< previous page page_274 next page >

Page 274
We use these questions as a checklist. The first three help us design the parts of the loop that control its execution. The next three help us design the processing within the loop. The last question reminds us to make sure that the loop exits in an appropriate manner.
Designing the Flow of Control
The most important step in loop design is deciding what should make the loop stop. If the termination condition isn't well thought out, there's the potential for infinite loops and other mistakes. So here is our first question:
What is the condition that ends the loop?
This question usually can be answered through a close examination of the problem statement. For example:
Key Phrase in Problem Statement
Termination Condition
Sum 365 temperatures
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
The loop ends when a counter reaches 365 (count-countrolled loop).
Process all the data in the file
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
The loop ends when EOF occurs (EOF-controlled loop).
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Process until 10 odd integers have been read
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
The loop ends when 10 odd numbers have been input (event counter).
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
The end of the data is indicated by a negative test score
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
The loop ends when a negative input value is encountered (sentinel-controlled loop).

Now we need statements that make sure the loop gets started correctly and statements that allow the loop to reach the termination condition. So we have to ask the next two questions:
How should the condition be initialized?
How should the condition be updated?
The answers to these questions depend on the type of termination condition.
Count-Controlled Loops
If the loop is count-controlled, we initialize the condition by giving the loop control variable an initial value. For count-controlled loops that use an iteration counter, the initial value is usually 1. If the process requires the counter to run through a specific range of values, the initial value should be the lowest value in that range.

 
< previous page page_274 next page >