beginnerArray ProblemsJava

Find the Sum of All Elements in an Array

Compute the total of all elements in an array using an accumulator loop.

Quick Answer

Start a running total at 0, then loop through the array adding each element to the total. When the loop ends, the total is the sum. Use a long accumulator when the values could add up beyond the int range to avoid overflow.

Problem Statement

Given an array of integers, compute the sum of all its elements. This is the foundational accumulator pattern: keep a running total and add each element to it as you walk the array.

Return the total. Watch for overflow when many large values are summed — a long accumulator is safer than an int.

Input: An array arr of length n.

Output: The sum of all elements as a single number.

Examples

Example 1
Input:  [4, 8, 15, 16, 23, 42]
Output: 108

4 + 8 + 15 + 16 + 23 + 42 = 108.

Example 2
Input:  [-3, -6, 9]
Output: 0

The negatives cancel the positive: -3 + -6 + 9 = 0.

Constraints

  • 0 <= n <= 10^6
  • Elements may be negative or zero

Think Before You Code

Reveal the questions to ask yourself first
  • What value should the running total start at before you add anything?
  • Which loop form reads every element exactly once?
  • Could the total overflow an int for large arrays or large values?

Hints

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

Hint 1
Keep a single variable that grows as you visit each element.
Hint 2
Initialise `sum = 0`, then add each element with `sum += arr[i]`.
Hint 3
For safety against overflow, make `sum` a `long` when values could be large.

Approach

Reveal the step-by-step approach

Accumulate every element into a running total.

  1. Set sum = 0 (use long for overflow safety).
  2. For each element x in the array, do sum += x.
  3. After the loop, sum holds the total — return it.

An empty array naturally yields 0 because the loop body never executes and sum keeps its initial value.

Dry Run

Walk through the example step by step

Summing [4, 8, 15, 16, 23, 42]:

element | sum += element | sum
--------+----------------+-----
4       | 0 + 4          | 4
8       | 4 + 8          | 12
15      | 12 + 15        | 27
16      | 27 + 16        | 43
23      | 43 + 23        | 66
42      | 66 + 42        | 108
------------------------- total = 108

Solution

Reveal the full Java solution
public class SumOfArray {
    public static long sum(int[] arr) {
        long sum = 0;
        for (int x : arr) {
            sum += x;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(sum(new int[]{4, 8, 15, 16, 23, 42})); // 108
        System.out.println(sum(new int[]{-3, -6, 9}));            // 0
    }
}

The accumulator pattern touches each element once and adds it to a running total, giving an O(n) solution with O(1) extra space. Using a long for the total means the running sum will not silently wrap around even when the individual int elements add up beyond the 32-bit range.

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

Common Mistakes

  • Initialising `sum` to `arr[0]` and also adding it in the loop, double-counting the first element.
  • Using an `int` accumulator that overflows for large arrays of large values.
  • Starting the loop at index 1 by mistake, skipping the first element.

Edge Cases to Test

  • Empty array [] — the sum is 0.
  • Array with negative numbers, whose contributions can cancel out to 0.
  • Large values that would overflow an int but fit in a long.

Interview Follow-Ups

  • How would you compute the average once you have the sum?
  • How would you sum only the even (or only the positive) elements?
  • How would you sum a 2D array's elements?

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