Skip to content
Preview · sample content · Explore all pages

Sum an integer array

Last updated: 28 Sept 20264 min read
guide
By AITrove Editorial

Use a loop and an accumulator, including the empty-array case.

Task

Return the sum of an integer array. Assume the sum fits in an int.

Example solution

Java
static int sum(int[] values) {
    int total = 0;
    for (int value : values) {
        total += value;
    }
    return total;
}

Check your work

{1, 2, 3} returns 6. An empty array returns 0. Decide separately how your program should handle a null input; this version assumes a non-null array.

Common Mistakes

Check empty inputs and invalid values before applying this operation to application data. State whether a method edits shared state or returns a separate value.

java-exercises
Storage details