GATE / CS ARCHIVE

GATE CSE 2020 / QUESTION 46

GATE CSE 2020 Q46

Programming in C · Scope, Lifetime & Storage Classes · Full GATE CSE 2020 paper

GATE 2020, Q46 2 marks · NAT
Report issue

Scope, Lifetime & Storage Classes

Question 46, GATE 2020: Find fun2(5) on the first invocation of these 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;
}
Tap to enlarge
Answer & solution

Official answer: 55

Step through it (18 steps)

Worked explanation

Use different names u and v in the trace for fun1’s and fun2’s separate static variables. Static initialization occurs once, not on every recursive call. The successive outer fun1 calls add 5,4,3,2,1 to u, making return values 5,9,12,14,15. At the corresponding fun2 entries, v becomes 5,14,26,40,55. The final fun2(0) returns 55 without changing it. When earlier calls unwind, they all return the same current static v=55; ignored recursive return values are not added again. This is why neither the triangular sum 15 nor the sum 5+4+3+2+1 is the final answer.

Derivation and answer

The two static variables named i belong to different functions and persist across calls. Starting from their initial zeros, fun1(5) increments its i five times and returns 5; subsequent fun1(4), fun1(3), fun1(2), fun1(1) return 9, 12, 14, 15 respectively. fun2 adds those five results into its own static i, so it returns 5+9+12+14+15=55. The recursive return values ignored inside fun1/fun2 do not undo updates to static storage. This assumes the displayed call is the first invocation, as intended.

Original paper, page 14 · Answer key