Sentinel Code

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

No, this is under control of the user, who terminates the loop by entering the sentinel value.

Sentinel Code

Here is a partially completed program that follows the logic of the flowchart:

import java.util.Scanner;

// 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 ) 
  {
    Scanner scan = new Scanner( System.in );
    int value;             // data entered by the user
    int sum = 0;           // initialize the sum

    // get the first value
    System.out.print( "Enter first integer (enter 0 to quit): " );
    value = scan.nextInt();

    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. But only two of the three aspects of a loop have been completed:

  1. The loop is initialized correctly.
  2. The condition in the while is correct.
  3. Preparing for the next iteration is not done yet.

QUESTION 3:

Complete the program by filling the blanks with the following:

System.out.print( "Enter an integer (or 0 to quit): " )
sum = sum + value
value = scan.nextInt()