Java Program to find the Average of N numbers - The Coding Shala
Home >> Java Programs >> Average of N numbers
Other Posts You May Like
In this post, we will learn how to find the Average of N numbers in Java.
Java Program to find the Average of N numbers
Write a Java program to find the Average of N numbers, take all the n numbers as input.
Example 1:
Input: number of elements is = 5
elements = 1, 2, 3, 4, 5
Output: 3
Explanation:
avg = (1 + 2 + 3 + 4 + 5) / 5 = 3
Java Program:
// Java program to find Average 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; } // find avg double avg = sum / num; System.out.print("Average of " + num + " numbers is: " + avg); 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 Average of 5 numbers is: 3.0
- Java Program to take input numbers into an Array
- Java Program to Add Two Numbers
- Java Program to find Sum of Digits of a Number
- Java Program to Swap Two Numbers
- Java Program to Multiply Two Numbers
Comments
Post a Comment