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 then what happens if this number happens to occur in the list to be added up?
With the value "0" as the sentinel, if that value occurs in the list to be added, it can be skipped without any problem (since skipping it affects the sum the same way as adding it in).
Here is the interesting part of the program again, with some additions to make the user 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 the second and third prompt.
Fill in the blank so that the program matches the suggested output.