Skip to main content

DSAPath7 mincore

Iteration

Iteration repeats a block of work with explicit loop state. It is often the clearest way to process arrays, simulate recurrences, and avoid call-stack overhead.

Why This Matters

Iteration makes state explicit. A loop variable, accumulator, and invariant often give a simpler implementation than recursive calls, especially for long linear scans.

Core Idea

A loop should have a loop invariant: a statement that remains true before and after each iteration.

Worked example: when summing an array, the invariant after processing index i is that the accumulator equals the sum of all elements before i.

PatternTypical use
counted looparrays and ranges
while loopunknown stopping time
two-pointer loopsorted arrays or windows
accumulator loopsums, counts, products

Common Mistakes

  • Off-by-one boundaries.
  • Mutating loop state in multiple places.
  • Using recursion when an iterative loop avoids stack depth risk.

Exercises

  • State the loop invariant for finding the maximum of an array.
  • Convert recursive factorial to a loop.
  • Identify the off-by-one error in a loop from 0 through n.

Next Topics

References

  • Bentley. Programming Pearls (2nd ed., 2000). Ch. 4.
  • Cormen, Leiserson, Rivest, Stein. Introduction to Algorithms (4th ed., 2022). Ch. 2.