Challenge your understanding of common recursive function patterns, principles, and behaviors with these scenario-based multiple-choice questions. This quiz focuses on recursive logic, base and recursive cases, and examples from programming and problem-solving contexts.
Which statement best describes the base case in the following recursive function for computing the factorial of a number: if n == 0, return 1; else return n * factorial(n-1)?
Explanation: The base case in any recursion is the condition upon which recursion terminates, preventing infinite calls. Here, n == 0 returning 1 fulfills that role. Decrementing n is part of progressing toward the base case but is not the base case itself. Multiplication and repeated function calls describe the recursive step, not the base case.
If a function recursively prints the value of n and then calls itself with n-1 until n reaches 1, what is the output for n = 3?
Explanation: Recursion processes each call before moving to the next, so printing n before the recursive call outputs 3, then 2, then 1 as each call executes. The sequence 1 2 3 would occur if the print was after the recursion. The other options represent either unordered or incorrect sequences.
In a recursive function for calculating the nth term of a sequence where term(n) = term(n - 1) + term(n - 2), which statement best identifies the recursive case?
Explanation: The recursive case is where the function definition refers to itself with smaller arguments—in this case, combining values from previous terms. Defining term(0) or returning 0 for n equals zero are base cases, not recursive ones. Stopping for negative values is sometimes used for error handling but not required for standard recursive cases.
Which of the following modifications will most likely cause infinite recursion in a countdown function that stops when n == 0?
Explanation: Without a proper base case check, such as n == 0, the function never stops calling itself and results in a stack overflow or infinite loop. Decrementing by 2 still eventually reaches 0 if n is even. Printing before recursion does not affect termination. Starting at zero triggers the base case immediately if present.
Which of the following problems is best solved using a recursive function pattern?
Explanation: The Fibonacci sequence is naturally defined recursively as each term depends on the two preceding terms. Sorting two elements or adding numbers doesn't need recursion and is inefficient for that purpose. Reading a single input value is a straightforward action requiring no recursion.