- Sum
1 + 2 + 3 + 4 + 5 = 15- Count
N = 5- Mean
15 / 5 = 3(matches the sample program output).
Find Average of N Numbers in Java
What you’ll learn
- The arithmetic mean formula and how it maps to a sum loop in Java.
- A Scanner-based program for
Ninteractive inputs, plus an array version without stdin. - Why
doubleand dividing by(double)Nmatter, and what breaks whenN = 0. - A small browser live preview for comma-separated numbers.
Overview
This walkthrough shows how to read N numeric inputs, accumulate their sum, and print the average (mean). A second program averages values already stored in an array — the same math, a different data path.
Two programs
Interactive Scanner loop for N numbers, plus a fixed array example (same mean idea).
Live preview
Paste comma-separated values and see count, sum, and mean instantly.
Interview polish
Guards for N <= 0, integer-division traps, and optional input error checks.
Prerequisites
You should know how to compile a small Java program and read from standard input with Scanner.
forloops,doubleandinttypes, andSystem.out.printforprintln.- Basic idea of integer division and why
sum / ncan truncate when both areint.
What is the average here?
The arithmetic mean (what we call average on this page) of numbers x1, ..., xN is
μ = (x1 + x2 + ... + xN) / N, provided N > 0.
In code you usually maintain one accumulator sum inside a loop, then divide once at the end.
Formal definition
Given real numbers x1, ..., xN with N ≥ 1, the sample mean is μ = (1/N) Σi=1N xi.
For 10, 15, 20, 25, 30, the sum is 100 and N = 5, so μ = 100 / 5 = 20.
This list matches the array example below; it is a clean sanity check when you print intermediate sums while debugging.
Intuition and examples
Think of the mean as “flattening” every value onto one number: if you replaced every entry in the list with that number, the total would match the original sum.
- Sum
10 + 15 + 20 + 25 + 30 = 100- Count
N = 5- Mean
100 / 5 = 20.
- Example
int sum = 3, n = 2sum / n- Evaluates as integer division: 1, not 1.5.
- Fix
- Use
doubleforsumor cast:(double) sum / n.
Takeaway: the math is simple; most bugs are type bugs or N = 0.
Live preview
Enter numbers separated by commas (spaces optional). The tool parses each token as a number, sums them, divides by the count, and prints count, sum, and mean. Empty input is rejected; at most 500 values are accepted.
- Try
1, 2, 3, 4, 5or10,15,20,25,30. - Press Run (or Enter).
- Compare with your Java output for the same list.
Algorithm
Goal: read N values, compute their arithmetic mean.
Read N
Decide how many numbers will be averaged. If N <= 0, stop or report an error before dividing.
Initialize sum = 0
Use a floating type such as double for sum so fractional inputs and non-integer means behave predictably.
Loop N times
Each iteration reads one value and adds it to sum.
Divide
Return sum / (double) N (or an equivalent expression) so the division is floating-point.
📜 Pseudocode
function averageOfN(n):
if n <= 0:
return error
sum ← 0
repeat n times:
read x
sum ← sum + x
return sum / nAverage of N numbers from stdin (Scanner)
Prompts for N values, reads them with Scanner, and returns sum / (double) n. Checks n > 0 before dividing.
import java.util.Scanner;
public class Main {
// Reads n double values from stdin; returns their mean, or 0.0 if n <= 0
static double findAverage(int n, Scanner scanner) {
if (n <= 0) {
return 0.0;
}
double sum = 0.0;
System.out.println("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
if (!scanner.hasNextDouble()) {
return 0.0;
}
double x = scanner.nextDouble();
sum += x;
}
return sum / n;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int n = 5;
if (n <= 0) {
System.out.println("N must be positive.");
return;
}
double result = findAverage(n, scanner);
System.out.printf("The average of the entered numbers is: %.6f%n", result);
}
}
}Explanation
The function keeps one running total and only divides after every term has been read.
if (n <= 0) return 0.0;Guard division. Without this, sum / n would attempt division by zero when n == 0.
scanner.hasNextDouble()Input safety. In production code you would handle invalid input gracefully instead of returning 0.0 immediately, but this check prevents the loop from mis-counting.
return sum / n;Floating division. Because sum is double, this performs a floating-point divide even though n is an int.
Average from a fixed array (no stdin)
Same mean as the formal example: 10, 15, 20, 25, 30 → mean 20. Useful when inputs are known at compile time or already loaded into memory.
public class Main {
static double averageFromArray(double[] a) {
if (a == null || a.length == 0) {
return 0.0;
}
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum / a.length;
}
public static void main(String[] args) {
double[] data = { 10, 15, 20, 25, 30 };
double avg = averageFromArray(data);
System.out.printf("Average = %.6f%n", avg);
}
}Explanation
a.length counts elements at runtime for this fixed array.
if (a == null || a.length == 0)Defensive API. Matches how you would harden library-style helpers in an interview follow-up.
sum += a[i];Streaming sum. You never need to copy or modify the array to compute its mean.
Optimization
One pass. You never need to store all values just to compute the mean; a running sum is enough unless other statistics are required.
Very large N or huge magnitudes. Kahan summation or wider types (such as BigDecimal for money) reduce rounding error; for many contest problems, double is enough.
Online mean. If values arrive in a stream, update with mean_k = mean_{k-1} + (x_k - mean_{k-1}) / k to avoid storing the full history.
Interview: state O(N) time and O(1) extra space for the streaming sum approach.
❓ FAQ
🔄 Input / output examples
When you run Example 1 with n = 5 and type five numbers on one line or across lines, Scanner consumes them in order.
| Typed after the prompt | Printed average (example) |
|---|---|
1 2 3 4 5 | 3.000000 |
10 15 20 25 30 | 20.000000 |
2.5 3.5 with n = 2 | 3.000000 |
Example 2 prints a single line:
Average = 20.000000Edge cases and pitfalls
Most real-world bugs are about types, divide-by-zero, or bad input — not the formula itself.
N == 0
Never divide by N until you know it is positive.
Integer division
If sum and n are both int, sum / n truncates. Promote to double before dividing.
Input failures
Non-numeric input can leave the Scanner at the wrong place. In robust code, give the user a chance to re-enter values instead of returning 0.0.
Huge sums
For extreme magnitudes or many terms, double rounding can matter; use BigDecimal or compensated summation when exact cents or high precision are required.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
Running sum over N inputs | O(N) | O(1) |
| Store all values then sum | O(N) | O(N) for the buffer |
Both sample programs on this page use only a few scalars besides input storage: auxiliary space is constant for the streaming approach.
Summary
- Mean: add all values, divide by
NforN > 0. - Code:
doubleaccumulator,Scanner(or an array) feeding a loop, divide byNasdouble. - Watch-outs:
N = 0, integer division, and unchecked input.
The arithmetic mean is the simplest “center” of a list: add every value, divide by how many there are. It matches what people usually mean by average in everyday language (and in most intro programming tasks).
9 people found this page helpful
