The value "0" in this program is the sentinel value. Could any other value be used?
No. You might decide that a special value like 9999 would be a good sentinel. But what happens if this number happens to occur in the list to be added up?
You also need to worry about errors in the data. It might be that the value 9999 would never occur in legitimate data, but users (and other data sources) make mistakes and unexpected values frequently occur.
With the value "0" as the sentinel, if "0" occurs in the list to be added, the user could just skip it (since skipping it affects the sum the same way as adding it in).
However, if the data comes from some other source (like a file of integers), then a "0" would not be skipped and the program would end too soon. This is a problem with sentinel controlled loops.
Here is the interesting part of the program again, with some additions to make the prompt more user friendly:
int count = 0; // number of integers read in // get the first value System.out.println( "Enter first integer (enter 0 to quit):" ); value = scan.nextInt(); while ( value != 0 ) { //add value to sum sum = sum + value; //increment the count ; //get the next value from the user System.out.println( "Enter the " + (count+1) + "th integer (enter 0 to quit):" ); value = scan.nextInt(); } System.out.println( "Sum of the " + count + " integers: " + sum ); } }
When the modified program is run, the user dialog looks like this:
C:\users\default\JavaLessons\chap18>java AddUpNumbers Enter first integer (enter 0 to quit): 12 Enter the 2th integer (enter 0 to quit): -3 Enter the 3th integer (enter 0 to quit): 4 Enter the 4th integer (enter 0 to quit): -10 Enter the 5th integer (enter 0 to quit): 0 Sum of the 4 integers: 3
Soon we will add additional statements to correct the dubious grammar in some of the prompts.
Fill in the blank so that the program matches the suggested output.