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

Home >> Java Programs >> Average of N numbers

 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


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

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala

Java Program to Reverse a String using Stack - The Coding Shala