Task 1 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.2 Array algorithms — summing an array

Lesson

Combining every element

Many array tasks follow one shape: scan the array and build up a result. To sum an array, keep an accumulator that starts at 0, then add each element to it as you traverse. When the loop ends, the accumulator holds the total.


Worked example

int[] nums = {3, 1, 4, 1, 5};
int sum = 0;
for (int i = 0; i < nums.length; i++) {
    sum = sum + nums[i];
}
System.out.println(sum);   // 14

▶ Try it: run this to add up the array. Change the values and re-run — the total follows.



To sum an array, an accumulator should start at...


What is the sum of {3, 1, 4}?


Type the sum this prints:

int[] a = {2, 4, 6};
int sum = 0;
for (int i = 0; i < a.length; i++) {
    sum = sum + a[i];
}
System.out.println(sum);

Order the lines to sum an array arr into sum.


True or false?