Practice question · Multiple choice
Every recursive function can be rewritten as a loop, and every loop can be rewritten recursively. Why does the choice between them still matter?
Hints
- Write a tree traversal as a loop. What do you have to build by hand?
- Now write array summation recursively. What did you gain?
Show the answer
C. Because one of them usually matches the shape of the problem.
Why
The equivalence is real and the ergonomics differ: a tree is a node with subtrees, so a recursive traversal mirrors it, where the iterative version maintains an explicit stack. Recursion costs a frame per call and tail-call optimisation removes that where it is guaranteed, so decide on clarity, and check depth when input could be large: a million-element descent exhausts Python’s stack.
Practise Recursion and Iterative Alternatives
The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on Recursion and Iterative Alternatives
- The lesson's factorial function is called as factorial(3). Order the events by when they happen in time.
- A recursive function that would need a million frames crashes in Python and runs fine in a language with…
- Select every statement the lesson supports about choosing recursion over iteration.
- A recursive function that has a base case cannot recurse forever.