Yes; each iteration of the loop will add a new number to the sum.
The loop will add each integer the user enters to a sum. A counting loop could do this if we knew how many integers were in the list. But often users don't know this in advance, or would find it annoying to find out. (If you have a column of integers, you would like to add them one by one until you reach the last one. It would be annoying if you needed to count them first.)
The idea of a sentinel controlled loop is that there is a special value (the "sentinel") that is used to say when the loop is done. In this example, the user will enter a zero to tell the program that the sum is complete. The general scheme of the program is given below:
import java.io.*; // Add up all the integers that the user enters. // After the last integer to be added, the user will enter a 0. // class addUpNumbers { public static void main (String[] args ) throws IOException { BufferedReader userin = new BufferedReader (new InputStreamReader(System.in)); String inputData; int value; // data entered by the user int sum = 0; // initialize the sum // 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 //get the next value from the user } System.out.println( "Sum of the integers: " + sum ); } }
The program is complete except for the loop body. Two of the three aspects of a loop are done:
while
is correct.