What distinguishes iteration from recursion, and direct from indirect recursion?
Iteration repeats a block by looping over it; recursion repeats it by having the block call itself — directly if the method calls itself, indirectly if it goes through another method that calls back.
* Three ways to repeat work — and indirect recursion is the one no single call site reveals. *
| Mechanism | In code | |
|---|---|---|
| Iteration | a section of code is traversed multiple times | for, while, do-while |
| Direct recursion | a method calls itself | factorial() calls factorial() |
| Indirect recursion | method A calls B, and B calls A again | isEven() ↔ isOdd() |
Both express "do this repeatedly", and anything one can compute the other can too — but they keep their state in different places. A loop keeps it in variables you declare and update; recursion keeps it on the call stack, one frame per pending call, each with its own copy of the parameters. That difference explains their trade-off:
- Recursion is clearer wherever the problem is defined recursively — trees, nested structures, divide-and-conquer. The code then mirrors the definition and needs no manual bookkeeping.
- Recursion costs a stack frame per level, and the stack is finite. Too deep and the program dies with a stack overflow, where a loop would have run happily.
Indirect recursion is the one to watch for — it is real recursion but invisible at any single call site, so the cycle A → B → A can be created by accident during refactoring and only shows up as a stack overflow at runtime.
Go deeper:
Recursion (computer science) — mutual recursion, recursion versus iteration, and how compilers flatten the easy cases.