Two ways to repeat
Most repetitive computation can be written either as a loop that updates variables or as a function that calls itself on a smaller subproblem. Both are valid, and choosing between them is a real engineering decision.
What recursion buys you
Recursion often mirrors the structure of the problem.
- Tree and graph traversals, divide and conquer, and naturally nested data read cleanly as recursion.
- The base case and recursive case make the logic explicit and easy to reason about.
What recursion costs
Each recursive call pushes a frame onto the call stack holding its local state.
- Deep recursion can exhaust the stack and crash with an overflow.
- Function calls add overhead that a tight loop avoids.
When iteration wins
Iteration keeps memory flat by reusing the same variables and avoids call overhead, which matters for hot loops and very deep computations. Many recursive routines can be rewritten as loops, sometimes with an explicit stack to mimic the recursion.
Key idea
Recursion expresses nested problems clearly but spends stack memory and call overhead, while iteration stays flat and fast, so match the style to the problem shape and depth.