Skip to content
Official PYQ · 2007

GATE CS 2007 Q42 — Recursion

Explain with AI

Consider the following C function:

int f(int n)
{ 
    static int r = 0;
    if (n <= 0) return 1;
    if (n > 3)
    {   r = n; 
        return f(n-2) + 2;
    }
    return f(n-1) + r;
}

What is the value of f(5)f(5)?

Choose one option
View worked solution

Answer: D

To find the value of f(5)f(5), we trace the recursive calls while keeping track of the static variable rr. Since rr is static, it retains its value across function calls and is initialized to 00 only once.

  1. Call f(5)f(5): Since 5>35 > 3, the static variable is updated to r=5r = 5. The function returns f(3)+2f(3) + 2.
  2. Call f(3)f(3): Since 3≤33 \le 3, it executes the last statement and returns f(2)+r=f(2)+5f(2) + r = f(2) + 5.
  3. Call f(2)f(2): Similarly, returns f(1)+r=f(1)+5f(1) + r = f(1) + 5.
  4. Call f(1)f(1): Returns f(0)+r=f(0)+5f(0) + r = f(0) + 5.
  5. Call f(0)f(0): Since 0≤00 \le 0, it returns 11.

Now, substituting the values back:

  • f(1)=f(0)+5=1+5=6f(1) = f(0) + 5 = 1 + 5 = 6
  • f(2)=f(1)+5=6+5=11f(2) = f(1) + 5 = 6 + 5 = 11
  • f(3)=f(2)+5=11+5=16f(3) = f(2) + 5 = 11 + 5 = 16
  • f(5)=f(3)+2=16+2=18f(5) = f(3) + 2 = 16 + 2 = 18

Thus, the value of f(5)f(5) is 18.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Recursion questions