GATE / CS ARCHIVE

GATE CSE 2009 / QUESTION 18

Recursive paired Fibonacci values

Programming in C · Recursion · Full GATE CSE 2009 paper

GATE 2009, Q18 1 mark · MCQ
Report issue

Recursion

Question 18, GATE 2009: C function fun(n, f_p) sets *f_p=1 and returns 1 if n≤1; otherwise t=fun(n−1, f_p), f=t+*f_p, *f_p=t, then returns f. main initializes x=15 and prints fun(5, &x). Choices A 6; B 8; C 14; D 15.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Step through it (13 steps)

At n=1 the function returns 1 and stores 1 through the pointer, overwriting the initial 15. For n=2, 3, 4, 5 the pairs(returned value, stored value) are(2, 1), (3, 2), (5, 3), (8, 5). The printed return value is 8, B.

The pointer is shared through all recursive calls, so its value must be tracked alongside the returned integer. The deepest call overwrites 15 with 1; thus 15 contributes nothing to the result. Each unwinding step returns the sum of the previous two Fibonacci-like values and stores the former return value for the next step. A trace gives n1:(1, 1), n2:(2, 1), n3:(3, 2), n4:(5, 3), n5:(8, 5). printf uses the returned 8, not the final stored 5.

Original paper, page 4