5.2 Looping | 233
odd number is read; it is an event counter. We initialize an event counter to 0 and
increment it only when a certain event occurs. The counter in the previous ex-
ample was an iteration counter; it was initialized to 1 and incremented during each
iteration of the loop.
How to Design Loops
It’s one thing to understand how a loop works when you look at it and something else again
to design a loop that solves a given problem. In this section, we look at how to design loops.
We can divide the design process into two tasks: designing the flow of control and design-
ing the processing that takes place in the loop. Each task consists of three parts: the task it-
self, initialization, and updating. It’s also important to specify the state of the code when it
exits the loop, because a loop that leaves variables and files in a mess is not well designed.
There are seven different points to consider in designing a loop:
1.What condition ends the loop?
2.How should the condition be initialized?
3.How should the condition be updated?
4.What is the process being repeated?
5.How should the process be initialized?
6.How should the process be updated?
7.What is the state of the code on exiting the loop?
We can 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, infinite loops and other mistakes could po-
tentially occur. Here is our first question:
What condition ends the loop?
We can usually answer this question by closely examining the problem statement.
For example:
Event counter A variable that
is incremented each time a par-
ticular event occurs
Key Phrase in Problem Statement Termination Condition
“Sum 365 temperatures”
“Process all data in the file”
“Process until 10 odd integers have been
read”
“The end of the data is indicated by a neg-
ative test score”
The loop ends when a counter reaches 365 (count-
controlled loop)
The loop ends when EOF occurs (EOF-controlled loop)
The loop ends when 10 odd numbers have been input
(event counter)
The loop ends when a negative input value is encoun-
tered (sentinel-controlled loop)