Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Use while loop to Write a program in java that reads and calculates the sum of a

ID: 3805298 • Letter: U

Question

Use while loop to Write a program in java that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input.

Do you need to declare a new variable for each input value? No.

Just use one variable named data to store the input value and use a variable named sum to store the total.

Whenever a value is read, assign it to data and, if it is not zero, add it to sum

Sample input:

Enter an integer (the input ends if it is 0): 2

Enter an integer (the input ends if it is 0): 3

Enter an integer (the input ends if it is 0): 4

Enter an integer (the input ends if it is 0): 0

Sample output:

The sum is 9

Explanation / Answer


// IntegerSum.java

import java.util.Scanner;

public class IntegerSum
{

   public static void main(String[] args)
   {
      
       Scanner scnr = new Scanner(System.in);
       int number;
       int sum = 0;

       while(true)
       {
           System.out.println("Enter an integer (the input ends if it is 0): ");
           number = scnr.nextInt();

           if(number == 0)
               break;
           sum = sum + number;
       }
      
       System.out.println("The sum is "+ sum);
   }

}

/*
output:

Enter an integer (the input ends if it is 0):
2
Enter an integer (the input ends if it is 0):
3
Enter an integer (the input ends if it is 0):
4
Enter an integer (the input ends if it is 0):
0
The sum is 9

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote