AP® Computer Science A · Unit 4 · Topic 4.5

Summing and Averaging an Array

Summing an array means walking it with an accumulator variable that adds each element in turn; averaging means dividing that final sum by the count, using double division so the decimal survives.

To sum an array you need one variable outside the loop, usually called sum, started at 0. The loop visits each index from 0 to arr.length - 1, and each pass does sum = sum + arr[i]. That variable is an accumulator: it carries the running total forward from one iteration to the next, so by the time the loop ends it holds the total of every element. The count is just arr.length, no loop needed, since arrays know their own size.

The average needs both pieces: the sum tells you the total, but the total alone is meaningless without knowing how many numbers produced it. 400 split across 4 scores averages to 100; the same 400 split across 8 scores averages to 50. So average = sum / count, but the division has to be done carefully. If sum and count are both int, Java performs integer division first, truncating any decimal part, and only afterward stores that truncated whole number into a double. Casting happens too late to help. The fix is forcing double division before the assignment, by casting one operand: (double) sum / count.

This same accumulator pattern — initialize before the loop, update inside it — is exactly what comes next for finding a maximum, counting matches, or filtering elements, like skipping negatives when averaging. Only the update line changes; the shape of the loop stays the same.

Key terms

Accumulator
A variable initialized before a loop that collects a running total or result as the loop executes.
Integer division
Division between two int values that discards any remainder, truncating toward zero.
Cast
An explicit conversion of a value from one type to another, such as (double) sum.
arr.length
The property of an array holding its total number of elements, used as the count.

Watch it explained

  1. How it worksHow does one accumulator collect a sum as the loop walks along the array?
  2. Worked exampleFind the sum and average of {90, 85, 78, 92}, tracing the accumulator each pass.
  3. Common mistakeWhy doesn't dividing an int sum by an int count give you the decimal average?
  4. Going furtherWhat changes when the average has to skip over any element that is negative?

Check yourself

Your turn1 of 2
Find the sum and, as a decimal, the average of 70, 65, 93, 29. What is the average?

End of topic.