(^234) | File Objects and Looping Statements
Now we need statements that make sure the loop starts correctly and statements that
allow the loop to reach the termination condition. We need 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 an
initial value to the loop control variable. For count-controlled loops in which the loop con-
trol variable is also 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.
The condition is updated by increasing the value of the counter by 1 for each iteration.
(Occasionally, you may come across a problem that requires a counter to count from some
value downto a lower value. In this case, the initial value is the greater value, and the counter
is decrementedby 1 for each iteration.) For count-controlled loops that use an iteration counter,
these are the answers to the two questions:
Initialize the iteration counter to 1.
Increment the iteration counter at the end of each iteration.
If the loop is controlled by a variable that counts an event within the loop, the control
variable usually is initialized to 0 and incremented each time the event occurs. For count-
controlled loops that use an event counter, here are the answers to the two questions:
Initialize the event counter to 0.
Increment the event counter each time the event occurs.
Sentinel-Controlled Loops In sentinel-controlled loops, a priming read may be the only initialization
required. You may also need to open the file in preparation for reading. To update the con-
dition, a new value is read at the end of each iteration. For sentinel-controlled loops, we an-
swer our two questions this way:
Open the file, if necessary, and input a value before entering the loop (priming read).
Input a new value for processing at the end of each iteration.
EOF-Controlled Loops EOF-controlled loops require the same initialization as sentinel-controlled
loops. You must open the file, if necessary, and perform a priming read. Updating the loop
condition happens implicitly; the input value reflects the success or failure of the operation.
However, if the loop doesn’t read any data, it never reaches EOF, so updating the loop con-
dition means the loop must keep reading data.
Flag-Controlled Loops In flag-controlled loops, the Boolean flag variable must be initialized to true
or falseand then updated when the condition changes. Here are the answers to the two
questions: