Recursion vs. iteration tradeoffs
Computer Science · Algorithms
Question 1 of 10
0A loop that repeats until a condition becomes false is an example of:
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Recursion vs. iteration tradeoffs explained
Recursion and iteration are two ways to repeat work. Iteration uses a loop, such as FOR or WHILE, while recursion repeats work by having a function call itself on a smaller version of the problem. Many problems can be solved either way, but each approach has different strengths.
Recursion often gives shorter, clearer code for problems that are naturally self-similar, such as traversing a tree or dividing a problem into halves. Each call needs its own space on the call stack to store its variables and its return point. Deep recursion therefore uses more memory, and it can fail with a stack overflow error if it goes too deep.
Iteration usually uses less memory, because a loop reuses the same variables. It also avoids the overhead of many function calls. Some languages can optimise certain recursive calls, but not all do, so it is safer not to assume they will.
A common mistake is to write a recursive function with no base case, so that it calls itself forever. Another is to assume one approach is always faster. The answer depends on the problem and on the language.
Worked example
Compute 5 factorial, written , with a loop and with recursion.
- Iteration: start with result = 1 and multiply it by 5, 4, 3, 2 and 1 in turn. This takes 5 loop steps and one variable.
- Recursion: factorial(5) = factorial(4), and so on down to factorial(1) = 1. This makes 5 calls, and the results return as 1, 2, 6, 24 and 120.
- Both methods give 120.
The same difference shows up with the simple recursive Fibonacci function. Finding F(5) = 5 this way (with F(0) = 0 and F(1) = 1) makes 15 function calls, while a loop needs only 4 additions.
What you will practise
104 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- Recursion uses:
- Iteration uses:
- Recursion risks:
- Iterative code often:
- Tree traversal is natural with:
- Every correct recursive function needs:
- Recursion typically keeps track of its pending calls on:
- A function that calls itself is called:
…and 96 more.