Java Program to find the Sum of N numbers - The Coding Shala
Home >> Java Programs >> Find Sum of N numbers
Other Posts You May Like
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
- Java Program to Find the Average of N numbers
- Java Program to Find the Sum of Digits of a Number
- Java Program to Swap Two Numbers
- Java Program to Print the sum of all elements of the array
- Java Program to Reverse a String
Comments
Post a Comment