Question
Consider the following recursive C function.
void get(int n)
{
if (n < 1) return;
get(n - 1);
get(n - 3);
printf("%d", n);
}
If get(6) function is being called in main() then how many times will the get() function be invoked before returning to the main()?
Official answer and solution
- Official answer
- B
- From
- Official GATE 2015 answer key
Solution
Formulate the recurrence relation for the total number of function calls and solve bottom-up.
Let denote the total number of invocations of get() generated when get(n) is executed.
- For any ,
get(n)is called once, testsif (n < 1) return;, and immediately returns without making any recursive calls.
Hence, for all .
- For ,
get(n)executes 1 call itself, followed by recursive callsget(n - 1)andget(n - 3):
Compute bottom-up:
Thus, the function get() is invoked 25 times (Option B).
B
Omitting the base case calls where n < 1, which are full function invocations that execute the function prologue and base condition.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2015 Computer Science and Information Technology (CS) Session 3
- Question
- 49 of 65, printed as CS Q.39
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.