Find Average of N Numbers in Java

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code Examples
Loops & I/O

What you’ll learn

  • The arithmetic mean formula and how it maps to a sum loop in Java.
  • A Scanner-based program for N interactive inputs, plus an array version without stdin.
  • Why double and dividing by (double)N matter, and what breaks when N = 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.

  • for loops, double and int types, and System.out.printf or println.
  • Basic idea of integer division and why sum / n can truncate when both are int.

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.

Mean sum ÷ count
Median middle after sort
Mode most frequent

Formal definition

Given real numbers x1, ..., xN with N ≥ 1, the sample mean is μ = (1/N) Σi=1N xi.

Worked example

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.

1 – 5 Mean 3
Sum
1 + 2 + 3 + 4 + 5 = 15
Count
N = 5
Mean
15 / 5 = 3 (matches the sample program output).
10 – 30 Mean 20
Sum
10 + 15 + 20 + 25 + 30 = 100
Count
N = 5
Mean
100 / 5 = 20.
Trap int / int
Example
int sum = 3, n = 2
sum / n
Evaluates as integer division: 1, not 1.5.
Fix
Use double for sum or 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.

  1. Try 1, 2, 3, 4, 5 or 10,15,20,25,30.
  2. Press Run (or Enter).
  3. Compare with your Java output for the same list.

Uses normal JavaScript floating point (not arbitrary precision).

Live result
Press “Run” to see count, sum, and mean.

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

Pseudocode
function averageOfN(n):
    if n <= 0:
        return error
    sum ← 0
    repeat n times:
        read x
        sum ← sum + x
    return sum / n
1

Average of N numbers from stdin (Scanner)

Prompts for N values, reads them with Scanner, and returns sum / (double) n. Checks n > 0 before dividing.

java
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.

2

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.

java
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

Add all N values to get a running sum, then divide that sum by N. In symbols: mean = (x1 + x2 + ... + xN) / N.
If inputs are fractional or you divide integers without casting, you can lose precision. Accumulating in double and dividing by (double)N avoids the classic int sum / n truncation bug when N does not divide the sum evenly.
Division by zero throws an exception or leads to invalid results. Always validate N > 0 before dividing, or return a sentinel value or error when N is invalid.
Scanner lets you read input in a simple, beginner-friendly way (for example nextInt or nextDouble). In production code you might use more efficient options, but for interviews Scanner is totally fine.
Reading and summing N values is O(N) time and O(1) extra space if you only keep a running sum. Storing all values in an array first is still O(N) time but O(N) space.
No. The mean is the sum divided by the count. The median is the middle value after sorting (or the average of the two middle values). They answer different questions about the same list.

🔄 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 promptPrinted average (example)
1 2 3 4 53.000000
10 15 20 25 3020.000000
2.5 3.5 with n = 23.000000

Example 2 prints a single line:

Console
Average = 20.000000

Edge cases and pitfalls

Most real-world bugs are about types, divide-by-zero, or bad input — not the formula itself.

Zero

N == 0

Never divide by N until you know it is positive.

Types

Integer division

If sum and n are both int, sum / n truncates. Promote to double before dividing.

I/O

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.

Overflow

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

ApproachTimeExtra space
Running sum over N inputsO(N)O(1)
Store all values then sumO(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 N for N > 0.
  • Code: double accumulator, Scanner (or an array) feeding a loop, divide by N as double.
  • Watch-outs: N = 0, integer division, and unchecked input.
Did you know?

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).

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful