Java Program to Calculate Average of N Numbers
This guide explains how to write a Java program to calculate the average of n numbers. We'll cover the formula, provide a complete Java program, and include an interactive calculator to test your understanding.
How to Calculate the Average
The average (or arithmetic mean) of a set of numbers is calculated by summing all the numbers and then dividing by the count of numbers. The formula is:
Average = (Sum of all numbers) / (Count of numbers)
For example, if you have the numbers 5, 10, and 15:
- Sum = 5 + 10 + 15 = 30
- Count = 3
- Average = 30 / 3 = 10
This is the basic formula used in our Java program.
Java Program to Calculate Average
Here's a complete Java program that calculates the average of n numbers entered by the user:
Note: This program uses the Scanner class to read user input. Make sure to import java.util.Scanner at the beginning of your program.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
double[] numbers = new double[n];
double sum = 0;
for (int i = 0; i < n; i++) {
System.out.print("Enter number " + (i + 1) + ": ");
numbers[i] = scanner.nextDouble();
sum += numbers[i];
}
double average = sum / n;
System.out.println("The average is: " + average);
scanner.close();
}
}
How the Program Works
- The program starts by creating a Scanner object to read user input.
- It prompts the user to enter the number of elements (n).
- It creates an array to store the numbers and initializes a sum variable to 0.
- Using a for loop, it prompts the user to enter each number and adds it to the sum.
- After collecting all numbers, it calculates the average by dividing the sum by n.
- Finally, it prints the average and closes the scanner.
Example Calculation
Let's walk through an example where we calculate the average of 4 numbers: 12, 15, 18, and 20.
Step-by-Step Calculation
- Sum = 12 + 15 + 18 + 20 = 65
- Count = 4
- Average = 65 / 4 = 16.25
The program would output: "The average is: 16.25"
Tip: You can modify the program to handle different data types or add input validation as needed.