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. The following is an annotated example for scores entered via the keyboard. It uses the concept of sentinel value. |
Initial comments |
/* Loops while( condition ) { statements } |
The fstream.h header can support both file and default I/O The stream report is created. |
#include<iostream.h> // header which contains the functions |
Variables are declared and initialized The first score is entered The heading of the list is created. |
float score ; // the test score entered |
The while loop. It will run as long as the scores entered are nonnegative. Note that the reading of the next score is done as the last statement. |
while ( score >= 0) // read the scores and add them up |
The if structure in this part makes sure that the count and average are not outputted to the file if the user terminates the loop at the very start ( avoids division by zero as well). |
if ( count > 0 ) |
The results are sent to the report file. We output the Done! Statement to the screen so that the user is informed. We could have given the name of the report file (better ?) |
cout << " \n \n Done! " ; |
The output to the default window and the contents of the report file are illustrated. |
cout << " \n\n Enter e(exit) to exit ..."; |