Skip to content
GATEiit

GATE CSE 2020 Q56: Return value of fun2(5) with static variables in recursion

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

Try it: numerical answer: type the value

Numerical answer. No negative marking.
Show answer and explanation

Answer: 55 (official GATE 2020 final answer key)

Concept used: A static local keeps its value across all calls, so fun1's counter keeps growing between calls from fun2.

First step: fun1(n) adds n to its static counter and returns the running total: fun1(5) returns 5, then fun1(4) returns 9, and so on.

Full step-by-step solution

Detailed working, common mistakes and linked mock tests will be available with a free GATEiit account. Log-in is coming soon.

Share this question

WhatsAppDownload image

Source: official GATE 2020 CS question paper and final answer key, organised by IIT Delhi. Question paper · Answer key