Java Program to Find Average of Numbers
average = sum / count.Examples
How to Think About It
Algorithm
Code
public class AverageCalculator { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; int sum = 0; for (int num : numbers) { sum += num; } double average = (double) sum / numbers.length; System.out.println("Average is " + average); } }
Dry Run
Let's trace the example numbers = {10, 20, 30, 40, 50} through the code
Initialize sum
sum = 0
Add first number
sum = 0 + 10 = 10
Add second number
sum = 10 + 20 = 30
Add third number
sum = 30 + 30 = 60
Add fourth number
sum = 60 + 40 = 100
Add fifth number
sum = 100 + 50 = 150
Calculate average
average = 150 / 5 = 30.0
Print average
Output: Average is 30.0
| Iteration | Number Added | Sum After Addition |
|---|---|---|
| 1 | 10 | 10 |
| 2 | 20 | 30 |
| 3 | 30 | 60 |
| 4 | 40 | 100 |
| 5 | 50 | 150 |
Why This Works
Step 1: Summing numbers
The code uses a loop to add each number to the total sum using sum += num.
Step 2: Calculating average
The average is found by dividing the sum by the count of numbers with average = (double) sum / numbers.length to get a decimal result.
Step 3: Printing result
The program prints the average using System.out.println to show the final output.
Alternative Approaches
import java.util.Scanner; public class AverageCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter number of elements: "); int n = scanner.nextInt(); int sum = 0; for (int i = 0; i < n; i++) { System.out.print("Enter number " + (i+1) + ": "); sum += scanner.nextInt(); } double average = (double) sum / n; System.out.println("Average is " + average); scanner.close(); } }
import java.util.Arrays; public class AverageCalculator { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; double average = Arrays.stream(numbers).average().orElse(0); System.out.println("Average is " + average); } }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through all numbers once to sum them, so time grows linearly with input size.
Space Complexity
Only a few variables are used regardless of input size, so space is constant.
Which Approach is Fastest?
The simple loop and the streams approach both run in O(n) time; streams add some overhead but improve readability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop | O(n) | O(1) | Basic and clear for beginners |
| User input with Scanner | O(n) | O(1) | Interactive programs needing user input |
| Java Streams | O(n) | O(1) | Concise code with modern Java features |