< previous page page_259 next page >

Page 259
loopCount = loopCount + 1;
When designing loops, it is the programmer's responsibility to see that the condition to be tested is set correctly (initialized) before the While statement begins. The programmer also must make sure the condition changes within the loop so that it becomes FALSE at some point; otherwise, the loop is never exited.
loopCount = 1;             ¼ Variable loopCount must be initialized
while (loopCount <= 10)
{
    .
    .
    .
    loopCount++;
           ¼ loopCount must be incremented
}
A loop that does not exit is called an infinite loop because, in theory, the loop executes forever. In the code above, omitting the incrementation of loopCount at the bottom of the loop leads to an infinite loop; the While expression is always TRUE because the value of loopCount is forever 1. If your program goes on running for much longer than you expect it to, chances are that you've created an infinite loop. You may have to issue an operating system command to stop the program.
How many times does the loop in our example execute9 or 10? To determine this, we have to look at the initial value of the loop control variable and then at the test to see what its final value is. Here we've initialized loopCount to 1, and the test indicates that the loop body is executed for each value of loopCount up through 10. If loopCount starts out at 1 and runs up to 10, the loop body is executed 10 times. If we want the loop to execute 11 times, we have to either initialize loopCount to 0 or change the test to
loopCount <= 11
Event-Controlled Loops
There are several kinds of event-controlled loops: sentinel-controlled, endof-file-controlled, and flag-controlled. In all of these loops, the termination condition 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 sentinel or trailer

 
< previous page page_259 next page >