Challenge your understanding of recursion in C programming with practical questions on function behavior, stack usage, and classic problem-solving techniques. This quiz is designed to reinforce concepts and help identify common pitfalls and effective recursive strategies.
When implementing a recursive function to compute factorial in C, what would happen if the base case is omitted or incorrectly defined?
Explanation: Without a proper base case, the recursion will never terminate, and each recursive call consumes stack space, eventually resulting in a stack overflow. Returning zero has no connection with missing base cases unless coded explicitly. Compilers cannot inherently detect or prevent logical errors like missing base cases. Code optimization cannot compensate for logical errors in recursive termination.
Suppose you want to print elements of an array in reverse order using recursion in C. What is the correct approach to achieve this?
Explanation: By first making a recursive call with the next element, then printing the current element, elements are printed in reverse order during the function’s unwinding phase. Using a for loop inside the recursive function makes the recursion redundant. Printing first before recursion results in the original order. Always calling with the zero index leads to infinite recursion over the same element.
Which statement best describes how recursion typically uses the C program’s stack during execution?
Explanation: Every recursive call adds a separate stack frame, storing local variables and return addresses until reaching the base case, after which frames are removed as the calls return. Recursion does not share a single stack frame, as each call is distinct. Stack growth for completed functions applies to all function calls, not just recursion, and recursion always uses the stack in C.
If a recursive C function used to compute the nth Fibonacci number is called as fibonacci(4), what is the expected output?
Explanation: The Fibonacci sequence (starting with 0, 1) calculates fibonacci(4) as fibonacci(3) + fibonacci(2), which equals 2 + 1 = 3. Option 5 corresponds to fibonacci(5), option 4 is not part of the sequence calculation, and 7 is much higher than the actual value. Using the correct formula ensures you select the right answer.
Which of the following problems is most naturally suited to be solved using recursion in C?
Explanation: Recursive solutions mirror the hierarchical structure of binary trees, making traversal (such as in-order) straightforward and elegant in C. Bubble sort and calculating averages are more efficiently completed with iteration. Integer multiplication does not inherently require recursion and is performed directly in most programs.