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

2.3 Iteration — accumulating a total

Lesson

Accumulating in a loop

A very common loop pattern: keep a running total (an accumulator) that starts at 0, and add to it on every pass. After the loop, the accumulator holds the combined result.


Worked example — sum of 1 to 4

int sum = 0;
int i = 1;
while (i <= 4) {
    sum += i;     // sum: 1, 3, 6, 10
    i++;
}
System.out.println(sum);   // 10

▶ Try it: run this (sum of 1..4 = 10). Change the 4 and re-run to sum a different range.



What does the sum loop above print?


Type what this prints:

int sum = 0;
int i = 1;
while (i <= 3) {
    sum += i;
    i++;
}
System.out.println(sum);

Put the lines in the right order to sum 1..n into sum.


True or false?