Skip to content
Official PYQ · 2020

GATE CS 2020 Q46 — Recursion

Explain with AI

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)\text{fun}2 (5) is _________

View worked solution

Answer: 55

To find the return value of fun2(5), we trace the execution step-by-step. Both functions use static variables, which retain their values across multiple function calls.

  • Let i1i_1 be the static variable inside fun1 (initially 00). Calling fun1(k) increments i1i_1 by kk and returns the updated value of i1i_1.
  • Let i2i_2 be the static variable inside fun2 (initially 00).

Tracing the recursive calls of fun2(5):

  1. fun2(5): Calls fun1(5). i1i_1 becomes 0+5=50 + 5 = 5. fun1(5) returns 55. i2=i2+5=0+5=5i_2 = i_2 + 5 = 0 + 5 = 5.
  2. fun2(4): Calls fun1(4). i1i_1 becomes 5+4=95 + 4 = 9. fun1(4) returns 99. i2=i2+9=5+9=14i_2 = i_2 + 9 = 5 + 9 = 14.
  3. fun2(3): Calls fun1(3). i1i_1 becomes 9+3=129 + 3 = 12. fun1(3) returns 1212. i2=i2+12=14+12=26i_2 = i_2 + 12 = 14 + 12 = 26.
  4. fun2(2): Calls fun1(2). i1i_1 becomes 12+2=1412 + 2 = 14. fun1(2) returns 1414. i2=i2+14=26+14=40i_2 = i_2 + 14 = 26 + 14 = 40.
  5. fun2(1): Calls fun1(1). i1i_1 becomes 14+1=1514 + 1 = 15. fun1(1) returns 1515. i2=i2+15=40+15=55i_2 = i_2 + 15 = 40 + 15 = 55.
  6. fun2(0): Base case (n≤0n \le 0). Returns i2=55i_2 = 55.

Thus, the final return value of fun2(5) is 55.

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

Published
Report a correction
Keep exploringMore Recursion questions