beginnerArray ProblemsJava

Find the Average of the Elements in an Array

Compute the arithmetic mean of an array by summing and dividing with floating-point division.

Quick Answer

Add all the elements into a running total, then divide that total by the number of elements. Do the division in floating-point (cast to double) so fractional averages are not truncated. The result is the arithmetic mean of the array.

Problem Statement

Given an array of integers, compute the average (arithmetic mean) of its elements. First accumulate the sum, then divide by the element count.

Return the average as a double. The key subtlety is that integer division would drop the fractional part, so the division must be done in floating point.

Input: A non-empty array arr of length n.

Output: The average of the elements as a double.

Examples

Example 1
Input:  [10, 20, 30, 40, 50]
Output: 30.0

Sum is 150, divided by 5 elements gives 30.0.

Example 2
Input:  [2, 3, 4, 5]
Output: 3.5

Sum is 14, divided by 4 elements gives 3.5 — the fractional part is kept.

Constraints

  • 1 <= n <= 10^6 (an empty array has no defined average)
  • Elements may be negative or zero

Think Before You Code

Reveal the questions to ask yourself first
  • How do you get the sum before you can divide?
  • Why would sum / n with two ints give the wrong answer?
  • What should happen when the array is empty?

Hints

Open them one at a time — try after each before revealing the next.

Hint 1
Compute the total first, then divide by how many elements there are.
Hint 2
If both `sum` and `n` are integers, the division truncates — cast to `double` first.
Hint 3
Return `(double) sum / n` so 14 / 4 becomes 3.5 rather than 3.

Approach

Reveal the step-by-step approach

Sum first, then divide in floating point.

  1. Accumulate sum over all elements (use long for overflow safety).
  2. Guard against an empty array, which has no defined average.
  3. Return (double) sum / arr.length — the cast forces floating-point division so the fractional part survives.

The cast is the crucial step: without it, 14 / 4 is integer division and yields 3.

Dry Run

Walk through the example step by step

Averaging [2, 3, 4, 5]:

step               | value
-------------------+----------------
sum = 2+3+4+5      | 14
count              | 4
(double) 14 / 4    | 3.5
------------------- average = 3.5

Solution

Reveal the full Java solution
public class ArrayAverage {
    public static double average(int[] arr) {
        if (arr.length == 0) {
            throw new IllegalArgumentException("Cannot average an empty array");
        }
        long sum = 0;
        for (int x : arr) {
            sum += x;
        }
        return (double) sum / arr.length;
    }

    public static void main(String[] args) {
        System.out.println(average(new int[]{10, 20, 30, 40, 50})); // 30.0
        System.out.println(average(new int[]{2, 3, 4, 5}));         // 3.5
    }
}

The average is just the sum divided by the count, but the division must happen in floating point. Casting sum to double before dividing makes Java use floating-point division, so an average like 3.5 is preserved instead of being truncated to 3. A long accumulator keeps the intermediate sum safe from overflow.

Time: O(n)Space: O(1)

Common Mistakes

  • Dividing two ints (`sum / n`), which truncates and reports 3 instead of 3.5.
  • Dividing by zero on an empty array instead of guarding against it.
  • Casting after the division (`(double)(sum / n)`), which still truncates first.

Edge Cases to Test

  • Single element [42] — the average is 42.0.
  • Averages with a fractional part, like [2, 3, 4, 5] giving 3.5.
  • Negative elements that pull the average below zero.

Interview Follow-Ups

  • How would you round the average to two decimal places for display?
  • How would you compute a running average as elements stream in?
  • How would you find the median instead of the mean?

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Explore the Java Full Stack program →
Chat with us