5.2 Looping | 235
Initialize the flag variable to trueor false, as appropriate.
Update the flag variable as soon as the condition changes.
In a flag-controlled loop, the flag variable essentially remains unchanged until it is time
for the loop to end. Then the code detects some condition within the process being repeated
that changes the value of the flag (through an assignment statement). Because the update
depends on what the process does, sometimes we have to design the process before we can
decide how to update the condition.
Designing the Process Within the Loop
Once we’ve decided on the appropriate looping structure, we can fill in the details of the
process. In designing the process, we must first decide what a single iteration should do.
Assume for a moment that the process will execute only once. What tasks must it perform?
What is the process being repeated?
To answer this question, we have to take another look at the problem statement. The def-
inition of the problem may require the process to sum up data values or to keep a count of
data values that satisfy some test. For example:
Count the number of integers in the file howMany.
This statement tells us that the process to be repeated is a counting operation.
Here’s another example:
Read a stock price for each business day in a week and compute the average price.
In this case, part of the process involves reading a data value. We conclude from our
knowledge of how an average is computed that the process also involves summing the
data values.
In addition to counting and summing, another common loop process is reading data,
performing a calculation, and writing out the result. Many other operations can appear in
looping processes. We’ve mentioned only the simplest here; we will look at some other
processes later on.
After we’ve determined the operations to be performed if the process is executed only
once, we can design the parts of the process that are necessary for it to be repeated cor-
rectly. We often have to add some steps to account for the fact that the loop executes more
than once. This part of the design typically involves initializing certain variables before the
loop begins and then reinitializing or updating them before each subsequent iteration.
How should the process be initialized?
How should the process be updated?
For example, if the process within a loop requires that several different counts and sums
be performed, each must have its own statements to initialize variables, increment counting
variables, or add values to sums. Just deal with each counting or summing operation by it-
self—that is, first write the initialization statement, and then write the incrementing or sum-
ming statement. After you’ve handled this task for one operation, go on to the next operation.