Sum algorithm in Java

The code below will find the sum of all elements in an array.

public int sum(int[] ray) {
    int sum = 0;
    for (int i = 0; i < ray.length; i++) {
        sum += ray[i];
    }
    return sum;
}

Let’s break down the pieces.

First, we’re creating a variable named sum to hold the sum of all the values in the array. We’re setting it to 0 because we haven’t found any values yet.

Then we loop through the array and add every element to sum so that at the end sum is holding the value of all elements added together.

And then we return.

Note that we used sum += ray[i] to add the values. We could have also used sum = sum + ray[i]. They’re the same thing.

With a while loop

The same logic would work with a while loop.

public int sum(int[] ray) {
    int sum = 0;
    int i = 0;
    while (i < ray.length) {
        sum += ray[i];
        i++;
    }
    return sum;
}

With a for each loop

And it would work with a for each loop as well.

public int sum(int[] ray) {
    int sum = 0;
    for (int i : ray) {
        sum += i;
    }
    return sum;
}

All three of these are doing the same thing. They’re starting with 0 and then adding every element of the array to it.

Video

This site contains affiliate links. If you click an affiliate link and make a purchase we may get a small commission. It doesn't affect the price you pay, but it is something we must disclose.