A very common usage of loops is
the repetitive reading of data. This reading may be from the keyboard
or from an existing data file which contains a long list of numbers.
In either case we need a method for signaling the end of the process.
A simple way is to use an unnatural value for the data entered, which will
then be picked up by our loop condition ( or another if statement) .
For example if we are entering scores of exams, it is safe to choose -1
as this unnatural score, the sentinel value, which will terminate the loop.
Hence the user of the program may be instructed to enter the value -1 after
all of the actual scores have been entered via the keyboard. Or, the
sentinel value -1 may be placed at the end of our data file. |
|
Notes: 1. Structure your program in a way that the sentinel value is NOT processed as regular data. For example the do ..while( cond. ) loop should not be used since it has to run at least one time. Another example is that the reading statement should be placed at the end of the while loop statements. 2. In the case of reading from a data file, an alternative approach is to let the program read to the end of the file. We will discuss this later under input failure. 3. An alternative way of terminating data entry is to specify the number of data to be entered (if known ahead of time ) and structure the program as a counting loop. We will discuss this later as well. |
|
|
© 2001 J.Y. Kazakia. All rights reserved