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.4 Iteration — accumulating with for

Lesson

Accumulating with a for loop

The accumulator pattern works the same in a for loop: a total declared before the loop, updated on each pass. Sums use += starting at 0; products use *= starting at 1.


Worked example — factorial of 4

int p = 1;
for (int i = 1; i <= 4; i++) {
    p *= i;      // p: 1, 2, 6, 24
}
System.out.println(p);   // 24

▶ Try it: run this (4! = 24). Change the 4 and re-run to see other factorials — try 5 and 6.



What does the factorial loop above print?


Type what this prints:

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

True or false?


Sort each accumulator start value by what it is used for.