Question

Consider the following C functions.

int fun1(int n) {
    static int i = 0;
    if (n > 0) {
        ++i;
        fun1(n - 1);
    }
    return (i);
}

int fun2(int n) {
    static int i = 0;
    if (n > 0) {
        i = i + fun1(n);
        fun2(n - 1);
    }
    return (i);
}

The return value of fun2(5) is _______.

Official answer and solution
Official answer
55
From
Official GATE 2020 answer key

Solution

Trace the execution of static variables across recursive calls to fun1 and fun2.

Notice that fun1 and fun2 each declare their own distinct static variable named i, both initialized to 0 once at the start of execution:

  • Let i1i_1 denote the static variable in fun1.
  • Let i2i_2 denote the static variable in fun2.

Behavior of fun1(k):

  • When fun1(k) is invoked with argument kk, if k>0k > 0 it increments i1i_1 by 1 and recursively calls fun1(k-1).
  • Thus, a call fun1(k) executes the ++i statement exactly kk times, increasing i1i_1 by kk, and returns the updated value of i1i_1.

Trace of fun2(5) step by step:

  • Initially: i1=0i_1 = 0, i2=0i_2 = 0.
  • Step 1 (n=5n = 5):
    • Calls fun1(5): increments i1i_1 by 5   ⟹  i1=5\implies i_1 = 5, returns 5.
    • Updates i2i_2: i2=i2+5=0+5=5i_2 = i_2 + 5 = 0 + 5 = 5.
    • Recursive call fun2(4).
  • Step 2 (n=4n = 4):
    • Calls fun1(4): increments i1i_1 by 4   ⟹  i1=5+4=9\implies i_1 = 5 + 4 = 9, returns 9.
    • Updates i2i_2: i2=i2+9=5+9=14i_2 = i_2 + 9 = 5 + 9 = 14.
    • Recursive call fun2(3).
  • Step 3 (n=3n = 3):
    • Calls fun1(3): increments i1i_1 by 3   ⟹  i1=9+3=12\implies i_1 = 9 + 3 = 12, returns 12.
    • Updates i2i_2: i2=i2+12=14+12=26i_2 = i_2 + 12 = 14 + 12 = 26.
    • Recursive call fun2(2).
  • Step 4 (n=2n = 2):
    • Calls fun1(2): increments i1i_1 by 2   ⟹  i1=12+2=14\implies i_1 = 12 + 2 = 14, returns 14.
    • Updates i2i_2: i2=i2+14=26+14=40i_2 = i_2 + 14 = 26 + 14 = 40.
    • Recursive call fun2(1).
  • Step 5 (n=1n = 1):
    • Calls fun1(1): increments i1i_1 by 1   ⟹  i1=14+1=15\implies i_1 = 14 + 1 = 15, returns 15.
    • Updates i2i_2: i2=i2+15=40+15=55i_2 = i_2 + 15 = 40 + 15 = 55.
    • Recursive call fun2(0).
  • Step 6 (n=0n = 0):
    • Condition n>0n > 0 is false; returns i2=55i_2 = 55.

All recursive returns pass back i2=55i_2 = 55. Thus, fun2(5) returns 55.

Final answer

55

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2020 Computer Science and Information Technology (CS)
Question
56 of 65, printed as CS Q.46
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.