dev only

Informal Runtime Analysis of Loops

Counting Iterations Without Running the Code

You can predict exactly how many times a loop runs just by reading its header:

for (int i = 3; i < 7; i++) { ... } // runs 6 - 3 + 1 = 4 times

The formula: largest value the loop variable reaches − smallest value + 1. For a < bound, the largest value is one less than the limit; for <=, it's the limit itself.

Nested Loops Multiply

A nested loop's total iteration count is outer iterations × inner iterations:

// 5 outer passes × 10 inner passes = 50 total iterations
for (int row = 0; row < 5; row++)
    for (int col = 0; col < 10; col++) { ... }

Why This Matters

Being able to predict a loop's iteration count without running it is a real debugging tool — if a loop is running way more (or fewer) times than expected, tracing through this formula by hand usually finds the off-by-one or the wrong bound immediately, faster than adding print statements and re-running.

Common Pitfalls

  • Forgetting to subtract 1 for a < bound. i < 7 starting at 3 reaches 3, 4, 5, 6 — four values, not seven minus three.
  • Multiplying the wrong two numbers for a nested loop. It's outer-count × inner-count-per-outer-pass, not outer-count + inner-count.

Key Takeaways

  • A loop's iteration count is largest reachable value − smallest value + 1.
  • Nested loops multiply: total iterations = outer count × inner count.
  • Counting iterations by hand is a fast way to catch an off-by-one bug before it turns into a mysterious runtime problem.

Derived from csawesome-2026: unit-2-selection-and-iteration/2.12-informal-runtime-analysis-of-loops.md (CSA 2.12)