Sum of n numbers in Java
Written by
Java Program to display sum of N numbers
In the following question, we are supposed to create a Java Source Code that will ask the user for integer number input N times and display the sum of its inputs altogether.
The standard algorithm will be:
- Enter and Store the Number of Integers to be Input.
- Run loop N times and keep asking integer input again and again.
- Perform Cumulative Sum of each integer given as input.
- After the loop terminates, print the result accordingly.
/* Program to Add N numbers user enters and displaying the sum using loop*/
import java.util.*;
class SumOfNumbers
{
public static void main()
{
Scanner inp=new Scanner(System.in);
System.out.print("\n Enter Number of Numbers to be Calculated: ");
int n=inp.nextInt();
int i,sum=0,z;
for(i=0;i<n;i++) //Entering N numbers
{
System.out.print("\n Enter: ");
z=inp.nextInt();
sum=sum+z; //Cumulative Sum
}
System.out.println("Sum of the numbers: "+sum);
}
}
Output:
Enter Number of Numbers to be Calculated: 5
Enter: 14
Enter: 25
Enter: 63
Enter: 87
Enter: 10
Sum of the numbers: 199