Use a loop and an accumulator, including the empty-array case.
Sum an integer array
Task
Return the sum of an integer array. Assume the sum fits in an int.
Example solution
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
