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()?

Choose one option
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 T(n)T(n) denote the total number of invocations of get() generated when get(n) is executed.

  • For any n<1n < 1, get(n) is called once, tests if (n < 1) return;, and immediately returns without making any recursive calls.
    Hence, T(n)=1T(n) = 1 for all n≤0n \le 0.
  • For n≥1n \ge 1, get(n) executes 1 call itself, followed by recursive calls get(n - 1) and get(n - 3):
    T(n)=1+T(n−1)+T(n−3)T(n) = 1 + T(n - 1) + T(n - 3)

Compute bottom-up:

  • T(0)=1,T(−1)=1,T(−2)=1T(0) = 1, \quad T(-1) = 1, \quad T(-2) = 1
  • T(1)=1+T(0)+T(−2)=1+1+1=3T(1) = 1 + T(0) + T(-2) = 1 + 1 + 1 = 3
  • T(2)=1+T(1)+T(−1)=1+3+1=5T(2) = 1 + T(1) + T(-1) = 1 + 3 + 1 = 5
  • T(3)=1+T(2)+T(0)=1+5+1=7T(3) = 1 + T(2) + T(0) = 1 + 5 + 1 = 7
  • T(4)=1+T(3)+T(1)=1+7+3=11T(4) = 1 + T(3) + T(1) = 1 + 7 + 3 = 11
  • T(5)=1+T(4)+T(2)=1+11+5=17T(5) = 1 + T(4) + T(2) = 1 + 11 + 5 = 17
  • T(6)=1+T(5)+T(3)=1+17+7=25T(6) = 1 + T(5) + T(3) = 1 + 17 + 7 = 25

Thus, the function get() is invoked 25 times (Option B).

Final answer

B

Common trap

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.