Next, let’s look at how to get the average of all elements in an array. It’s going to build off of the array sum algorithm from last time and the code will look pretty similar.

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

Most of the logic is the same as calculating the sum. In fact, we’re calculating the sum again. The difference is what we’re doing before it returns.

Notice that this method is returning a `double`

instead of an `int`

. We want the decimals, so we can’t use `int`

here. But that also means that we have to do a little bit of work on the last line to get the average as a `double`

.

If we just did `sum / ray.length`

, both of which are `int`

values, the result would be an `int`

and any decimals would be truncated. Not what we want.

So what we do is add a cast do `sum`

and it becomes `(double)sum`

. Now it’s a `double`

and we can divide it by `ray.length`

and get a `double`

as a result. We could have also cast `ray.length`

or cast both and it would have worked the same way. We also could have used `double`

instead of `int`

for `sum`

and it would have worked perfectly well.

The same logic would work with a `while`

loop.

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

This time I did make `sum`

a `double`

just so you could see it both ways.

And a for each would be fine as well.

```
public double average(int[] ray) {
double sum = 0;
for (int i : ray) {
sum += i;
}
return sum / ray.length;
}
```

This post is part of a series of algorithms used in array manipulation

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.