Skip to main content
๐Ÿ“œ 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 break inside 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.