Java Program to find the Sum of N numbers - The Coding Shala

Home >> Java Programs >> Find Sum of N numbers

 In this post, we will learn how to find the Sum of N numbers in Java.

Java Program to Find the Sum of N numbers

Write a Java Program to Find the Sum of N numbers, take all the numbers as input using Scanner, and print the sum of n numbers.

Example 1:
Input: elements: 1,2,3,4,5
Output: 15

Java Program: 

// Java program to find Sum of N numbers

import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) { 
		Scanner sc = new Scanner(System.in);
		
		System.out.println("How many numbers are there?");
		int num = sc.nextInt();
		
		double sum = 0;
		for(int i = 0; i < num; i++) {
			System.out.println("Enter " + (i+1) + " element: ");
			int n = sc.nextInt();
			sum = sum + n;
		}
		
		
		System.out.print("Sum of " + num + " numbers is: " + sum);
		
		sc.close();
	}
}

Output: 

How many numbers are there?
5
Enter 1 element: 
1
Enter 2 element: 
2
Enter 3 element: 
3
Enter 4 element: 
4
Enter 5 element: 
5
Sum of 5 numbers is: 15.0


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala