Skip to content
Official PYQ · 2004

GATE CS 2004 Q31 — Recursion

Explain with AI

Consider the following C function:

int f(int n)
{
    static int i = 1;
    if(n >= 5) return n;
    n = n+i;
    i++;
    return f(n);
}

The value returned by f(1)f(1) is:

Choose one option
View worked solution

Answer: C

To find the value returned by the call f(1), we trace the execution step-by-step. Note that the variable i is declared as static, which means it is initialized only once and retains its updated value across all recursive calls.

Step-by-Step Execution Trace:

  1. First Call: f(1)
    • n = 1, and i is initialized to 1.
    • The condition n >= 5 (1≥51 \ge 5) is false.
    • n = n + i   ⟹  n=1+1=2\implies n = 1 + 1 = 2.
    • i++   ⟹  i\implies i becomes 2.
    • Calls f(2).
  2. Second Call: f(2)
    • n = 2, and i is currently 2.
    • The condition n >= 5 (2≥52 \ge 5) is false.
    • n = n + i   ⟹  n=2+2=4\implies n = 2 + 2 = 4.
    • i++   ⟹  i\implies i becomes 3.
    • Calls f(4).
  3. Third Call: f(4)
    • n = 4, and i is currently 3.
    • The condition n >= 5 (4≥54 \ge 5) is false.
    • n = n + i   ⟹  n=4+3=7\implies n = 4 + 3 = 7.
    • i++   ⟹  i\implies i becomes 4.
    • Calls f(7).
  4. Fourth Call: f(7)
    • n = 7.
    • The condition n >= 5 (7≥57 \ge 5) is true.
    • The function immediately returns n, which is 7.

Thus, the value returned by f(1) is 7.

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

Published
Report a correction
Keep exploringMore Recursion questions