Sunday, November 3, 2013

Java while loop example

Write a program that gets several integers from the user. Sum up all the integers they give you. Stop looping when they enter a 0. Display the total at the end.
You must use a while loop.

Example:

I will add up the numbers you give me.
Number: 6
The total so far is 6
Number: 9
The total so far is 15
Number: -3
The total so far is 12
Number: 2
The total so far is 14
Number: 0

The total is 14.

Solution: 

//Importing the Scanner Class
import java.util.Scanner;

public class Question3 {
 
 public static void main(String args[]){
  //Creating Scanner object
  Scanner input = new Scanner(System.in);
  
  //Prompting user for input
  System.out.println("I will add up the numbers you give me.");
  int i=0;
  
  System.out.print("Number: ");
  //Reading first number
  i = input.nextInt();
  int sum=i;
  
  while(i!=0){
   System.out.println("The total so far is "+sum);
   System.out.print("Number: ");
   i = input.nextInt();
   //Summing
   sum=sum+i;
  }
  //Displaying final result.
  System.out.println("The total is "+sum);
 }
}

No comments:

Post a Comment