5.2 Looping | 225
A loop that never exits is called an infinite loopbecause, in theory, the loop executes for-
ever. In the preceding code, omitting the incrementation of loopCountat the bottom of the loop
leads to an infinite loop; the whileexpression is always true because the value of loopCount
is forever 1. If your application runs for much longer than expected, chances are that you’ve
created an infinite loop. In such a case, you may have to issue an operating system command
to stop the application.
How many times does the loop in our example execute—9 or 10? To answer this ques-
tion, we must look at the initial value of the loop control variable and then at the test to see
its final value. Here we’ve initialized loopCountto 1, and the test indicates that the loop body
is executed for each value of loopCountup through 10. If loopCountstarts at 1 and runs up to
10, the loop body is executed 10 times. If we want the loop to execute 11 times, we must ei-
ther initialize loopCountto 0 or change the test to
loopCount <= 11
Event-Controlled Loops
There are several kinds of event-controlled loops; we examine two of them here: sentinel-
controlled and end-of-file-controlled. In all event-controlled loops, the termination condi-
tion depends on some event occurring while the loop body is executing.
Sentinel-Controlled Loops Loops often are used to read in and process long lists of data. Each
time the loop body is executed, a new piece of data is read and processed. Often a special data
value, called a sentinelor trailer value, is used to signal the code that no more data remain to
be processed. Looping continues as long as the data value read is notthe sentinel; the loop
stops when the code recognizes the sentinel. In other words, reading the sentinel value is the
event that controls the looping process.
A sentinel value must be something that never shows up in the normal input to an ap-
plication. For example, if an application reads calendar dates, we could use February 31 as
a sentinel value:
// This code is incorrect
while( !date.equals("0231") )
{
date = dataFile.readLine(); // Get a date
. // Process it
.
.
}
There is a problem in the loop this example. The value of dateis not defined before the first
pass through the loop. Somehow we have to initialize this String. We could assign an arbi-
trary value to it, but then we would run the risk that the first value input will be the sentinel
value, which would then be processed as data. Also, it’s inefficient to initialize a variable
with a value that is never used.