Complete Add Up Program

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:

The complete program is given below.

Complete Add Up Program

Here is the complete program. Notice how the loop condition always has a "fresh" value to test. To make this happen, the first value needs to be input before the loop starts. The remaining values are input at the bottom of the loop body.

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
      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 statements that get the first value and the statements that get the remaining values are nearly the same. This is OK. If you try to use just one set of input statements you will dangerously twist the logic of the program.

QUESTION 4:

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