What would happen if the very first integer the user entered were "0"?
The loop body would not execute even once. The program would print out:
Sum of the integers: 0
Often the data that a loop processes is the result of a previous part of the program. That part of the program might not have produced any data. For example, a monthly checking account report from a bank has to deal with those months where the customer has written no checks.
Here is an example of this program working, I did this by copying the program to the clipboard, pasting into NotePad, saving as a file, compiling, and running. (The color was added later.)
C:\users\default\JavaLessons\chap18>java addUpNumbers Enter first integer (enter 0 to quit): 12 Enter next integer (enter 0 to quit): -3 Enter next integer (enter 0 to quit): 4 Enter next integer (enter 0 to quit): 0 Sum of the integers: 13
Here is the relevant section of the program:
// get the first value System.out.println( "Enter first integer (enter 0 to quit):" ); inputData = userin.readLine(); value = Integer.parseInt( inputData ); while ( value != 0 ) { //add value to sum sum = sum + value; //get the next value from the user System.out.println( "Enter next integer (enter 0 to quit):" ); inputData = userin.readLine(); value = Integer.parseInt( inputData ); } System.out.println( "Sum of the integers: " + sum ); } }
The value "0" in this program is the sentinel value. When the loop starts up, it is not known how many times the loop will execute. Even the user might not know; there might be a big, long list of numbers to be added and the user might not know exactly how many there are.
The value "0" in this program is the sentinel value. Could any other value be used?