Java Program to Add n Numbers
This post covers a program in Java that will find and print the sum of n numbers entered by user at run-time of the program.
Find Sum of n Numbers without Array in Java
The question is, write a Java program to find the sum of n numbers. The value of n and n numbers
must be received by user at run-time. The answer to this question, is the program given below:
import java.util.Scanner;
public class CodesCracker
{
public static void main(String[] args)
{
int n, i, num, sum=0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Value of n: ");
n = scan.nextInt();
System.out.print("Enter " +n+ " Numbers: ");
for(i=0; i<n; i++)
{
num = scan.nextInt();
sum = sum + num;
}
System.out.println("\nSum = " +sum);
}
}
The sample run of above program with user input 3 as value of n and 50, 60, 70 as three numbers, is
shown in the snapshot given below:
Find Sum of n Numbers using Array in Java
This program uses array to do the same job as of previous program. That is, to find and print the sum of n given numbers:
import java.util.Scanner;
public class CodesCracker
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Value of n: ");
int n = scan.nextInt();
int[] arr = new int[n];
System.out.print("Enter " +n+ " Numbers: ");
for(int i=0; i<n; i++)
arr[i] = scan.nextInt();
int sum = 0;
for(int i=0; i<n; i++)
sum += arr[i];
System.out.println("\nSum = " +sum);
}
}
This program produces the same output as of previous program.
Same Program in Other Languages
Java Online Test
« Previous Program
Next Program »