Explore the fundamentals of recursion with engaging questions focused on flow control, base cases, and call stack behavior. This quiz is designed to reinforce your understanding of recursive logic, clarify common misconceptions, and strengthen problem-solving techniques in computer science.
Why is it essential for every recursive function to have a proper base case, such as in the example of calculating factorial(n)?
Explanation: A proper base case is necessary so the recursive function knows when to stop calling itself; otherwise, it may cause infinite calls and eventually a stack overflow. Optimizing memory is a benefit but not the primary reason for a base case. Syntax errors are related to incorrect code structure, not missing a base case. Skipping all recursive calls would defeat the purpose of recursion.
If a recursive function calls itself three times before reaching its base case, how many total function instances are on the call stack at that base case?
Explanation: The original call and three recursive calls result in four instances on the call stack before any begin returning. Two would only be possible after some returns have occurred, while six overestimates the number. One is incorrect because there is more than just the base function still active before unwinding begins.
For which scenario is recursion generally preferred over iteration, for example, when traversing a tree structure?
Explanation: Recursion is ideal for problems like tree traversals that exhibit hierarchical or self-similar patterns. Minimizing execution time is not always guaranteed with recursion; sometimes, iteration is faster. Variables can still be declared in iterative approaches. Recursion is just one of several ways to achieve repeated logic.
What is the most common cause of a stack overflow in recursive functions, such as summing the elements of a list?
Explanation: A missing or incorrect base case leads to infinite recursion, which rapidly fills up the call stack and causes overflow. Simple loops do not involve recursion, so a 'for' loop is unrelated. Memory usage alone does not cause stack overflow unless caused by recursion depth. Parameter order might result in logic errors but not stack overflow by itself.
Given a function that prints a number and then calls itself with a smaller argument, such as print(n) and then call with n-1 until n equals 0, in what order are the numbers printed?
Explanation: The function prints the current number before making the recursive call, producing a decreasing sequence like 3, 2, 1. Increasing order would result if the print happened after the recursive call. Random order is not possible due to the deterministic sequence. Output is not delayed until the base case; printing occurs before recursion.