GATE / CS ARCHIVE

GATE CSE 2017 SET 1 / QUESTION 35

GATE CSE 2017 Set 1 Q35

Programming in C · Recursion · Full GATE CSE 2017 Set 1 paper

GATE 2017 Set 1, Q35 2 marks · MCQ
Report issue

Recursion

Question 35, GATE 2017: Functions: void fun1(int n) { if(n==0)return; printf("%d",n); fun2(n-2); printf("%d",n); }
void fun2(int n) { if(n==0)return; printf("%d",n); fun1(++n); printf("%d",n); }
What does fun1(5) print? A 53423122233445; B 53423120112233; C 53423122132435; D 53423120213243. Assume declarations needed for mutual calls.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step through it (17 steps)

1. Record entry prints separately from return prints. fun1(5) prints 5 and calls fun2(3); that prints 3, increments its local n to 4, then calls fun1(4).

2. Continuing yields entries fun1(4),fun2(2),fun1(3),fun2(1),fun1(2),fun2(0). The zero call prints nothing. The nonzero entry sequence is 5,3,4,2,3,1,2.

3. Unwind in reverse: fun1(2) prints 2; fun2’s local n is now 2, so it prints 2; subsequent exits print 3,3,4,4,5. Entry string 5342312 plus exit string 2233445 gives 53423122233445, A.

Original paper, page 16 · Answer key