The GATE Grind

GATE 2020 CS – Question 56

Programming and Data Structures · Recursion · 2 marks · Numerical answer

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 ______.

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 55 to 55

Explanation

`fun1` has a `static int i`, so it keeps growing across calls: each call to `fun1(n)` recurses `n` times (increasing `i` once per level) and returns the current `i`.

`fun2(5)` calls `fun1(n)` for $n=5,4,3,2,1$ in turn and accumulates the results in its **own** static `i`.

`fun2(5)` returns its static `i`, which is **55**.

More Recursion questions

All Recursion questions →