๐ WAYPOINT LESSON
Nested loops as arithmetic
โญโญโญ advancedโณ 10 min read๐ Lesson 167 of 256
Recognize the sum shapes (constant, series, halving) instead of simulating every pass โ small-case simulation plus generalization.
Nested loops and invariants. When the loop nest is too deep to simulate fully, find the pattern of the inner loop's total:
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
count++;
}
}
count gains n + (n-1) + ... + 1 โ n(n+1)/2. Recognizing the
arithmetic series beats simulating 6 rows, and the exam counts on you
seeing it. The general kit:
- Sum shapes: constant per pass โ multiply; growing per pass โ series; halving per pass โ logarithmic.
- Order of updates: does the inner loop restart the accumulator? Does the outer loop read what the inner wrote?
- Break/continue position: a
breakinside the inner loop changes the shape of the series, not just the count.
When in doubt on the real exam, simulate a small n (2 or 3) and generalize โ small-case simulation plus pattern is faster and safer than full tracing.