Computer Science I / Recursion and Iterative Alternatives
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
  1. Write a tree traversal as a loop. What do you have to build by hand?
  2. 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.

Read the lesson: Recursion and Iterative Alternatives →

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