Problem Solving Fundamentals · Recursion

When to loop instead

recursion versus iteration

When to loop instead

You have written a recursive function that walks a list, and it works. Now a teammate asks why you did not write a for loop. Both produce the same answer. Choosing between them is not about correctness — it is about which one reads more clearly for this problem, and which one is safer at scale.

Reach for recursion when the data is itself recursive. A nested array, a folder tree, a grammar: these have no fixed depth, and a loop over them needs a stack you maintain by hand. A recursive function matches that shape directly. Handle one level, hand the rest to a smaller copy of itself, and the code mirrors the structure of the data.

Reach for iteration when the work is a flat pass over a list, or when the depth could be large and unpredictable. A loop keeps one frame instead of one per item, so it will not overflow on a long input, and it is usually faster because it skips the call overhead. Counting, summing, and filtering a list of known length are loop-shaped.

The honest test is readability. If the recursive version is clearly shorter and tracks the data's shape, keep it. If you find yourself adding an accumulator and a helper function only to make recursion fit, the loop is the clearer tool. When the depth is unbounded, prefer the loop either way — recursion costs stack, and the stack is finite.

You are about to answer a quiz on choosing between recursion and iteration.

  1. Recursion fits data whose depth you cannot know in advance.
  2. A recursion that walks a list spends one stack ___ per element.
  3. A loop keeps a single stack frame no matter how long the input is.
  4. For a flat pass over a long list, a ___ is usually the clearer and safer tool.
  5. If the recursive version needs an accumulator and a helper only to make it fit, the loop is often clearer.
  6. Choosing between recursion and iteration is mainly about ___ and safety, not correctness.