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.
0
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}?
{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.
arr
sum
True or false?