4.7. Sentinel-Controlled Repetition

Let’s generalize the class average problem. Consider the following problem:

Develop a class average program that processes grades for an arbitrary number of students each time it’s run.

In the previous example, the problem statement specified the number of students, so the number of grades (10) was known in advance. In this example, no indication is given of how many grades the user will enter during the program’s execution. The program must process an arbitrary number of grades. How can the program determine when to stop the input of grades? How will it know when to calculate and print the class average?

To solve this problem, we can use a special value called a sentinel value (also called a signal value, a dummy value or a flag value) to indicate “end of data entry.” After typing the legitimate grades, the user types the sentinel value to indicate that the last grade has been entered.

The sentinel value must be chosen so that it’s not confused with an acceptable input value. Grades are normally nonnegative integers, so –1 is an acceptable sentinel value. Thus, a run of the program might process inputs such as 95, 96, 75, 74, 89 and –1. The program would then compute and print the class average for the grades 95, 96, 75, 74 and 89. Since –1 is the sentinel value, it should not enter into the averaging calculation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.171.58