< previous page page_313 next page >

Page 313
code.) You can remove the double slashes if you need to use the statements again.
8. An ounce of prevention is worth a pound of debugging. Use the checklist questions, write the loop invariant, and design your loop correctly at the outset. It may seem like extra work, but it pays off in the long run.
Summary
The While statement is a looping construct that allows the program to repeat a statement as long as an expression is TRUE. When the expression becomes FALSE, the statement is skipped, and execution continues with the first statement following the loop.
With the While statement you can construct several types of loops that you will use again and again. These types of loops fall into two categories:
count-controlled loops and event-controlled loops.
In a count-controlled loop, the loop body is repeated a specified number of times. You initialize a counter variable right before the While statement. This variable is the loop control variable. The control variable is tested against the limit in the expression of the While. The last statement in the loop body increments the control variable.
Event-controlled loops continue executing until something inside the body signals that the looping process should stop. Event-controlled loops include those that test for a sentinel value in the data, end-of-file, or a change in a flag variable.
Sentinel-controlled loops are input loops that use a special data value as a signal to stop reading. EOF-controlled loops are loops that continue to input (and process) data values until there is no more data. To implement them with a While statement, you must test the state of the input stream by using the name of the stream variable as if it were a Boolean variable. The test yields zero (FALSE) when there are no more data values. A flag is a variable that is set in one part of the program and tested in another. In a flagcontrolled loop, you must set the flag before the While, test it in the expression, and change it somewhere in the body of the loop.
Counting is a looping operation that keeps track of how many times a loop is repeated or how many times some event occurs. This count can be used in computations or to control the loop. A counter is a variable that is used for counting. It may be the loop control variable in a count-controlled loop, an iteration counter in a counting loop, or an event counter that counts the number of times a particular condition occurs in a loop.
Summing is a looping operation that keeps a running total of certain values. It is like counting in that the variable that holds the sum is initialized outside the loop. The summing operation, however, adds up unknown values; the counting operation adds a constant (1) to the counter each time.

 
< previous page page_313 next page >