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.
for
+=
*=
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.
4
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.