Which scenario best explains when recursion is preferred over iteration?
Think about problems that break down into smaller similar problems.
Recursion is preferred when the problem naturally breaks down into smaller subproblems, such as traversing trees or solving divide-and-conquer problems.
What is the output of the following code?
def factorial_recursive(n): if n == 0: return 1 return n * factorial_recursive(n-1) def factorial_iterative(n): result = 1 for i in range(1, n+1): result *= i return result print(factorial_recursive(4)) print(factorial_iterative(4))
Calculate 4! (4 factorial) carefully.
4 factorial is 4*3*2*1 = 24. Both functions compute factorial correctly for input 4.
What error or output will this code produce?
def infinite_recursion(): return infinite_recursion() infinite_recursion()
Think about what happens when a function calls itself endlessly without a base case.
This code causes a RecursionError because it calls itself infinitely without stopping.
Which situation best explains when iteration is preferred over recursion?
Think about memory use and simple repeated tasks.
Iteration is preferred when the task is a simple repeated process and memory efficiency is important, avoiding the overhead of recursive calls.
You want to compute the 30th Fibonacci number efficiently. Which approach is best?
Consider time and memory efficiency for large inputs.
Iteration is efficient and uses constant memory for Fibonacci numbers. Simple recursion without caching is very slow due to repeated calculations. Memoization helps recursion but iteration is simpler and faster here.
