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
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 Symantec Java! JustInTime Compiler Version 210.063 for JDK 1.1.3 Copyright (C) 1996-97 Symantec Corporation 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.