What would happen if the very first integer the user entered were 0 ?

Answer:

The loop body would not execute even once. The program would print out:

Sum of the integers: 0

Example Program Run

The user must have a way to say that there are no integers to add. This might seem dumb in a small program like this, but in larger programs with many options and more complicated processing it is often important to be able to skip over a loop. Sometimes beginning programmers assume that there will always be some numbers to add. Big mistake.

Often a loop processes data that is the result of a previous part of the program. That previous part of the program might not have produced any data. For example, a monthly checking account report must deal with those months where the customer has written no checks.

Here is an example run of this program, with color added to match the Java statements:

C:\users\temp>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):" );
    value = scan.nextInt();

    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):" );
      value = scan.nextInt();
    }

    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 long list of numbers to be added and the user might not know in advance how many there are.

QUESTION 5:

The value 0 in this program is the sentinel value. Could any other value be used?