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.
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.
4
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.
sum
True or false?