GATE / CS ARCHIVE

GATE CSE 2016 SET 1 / QUESTION 35

GATE CSE 2016 Set 1 Q35

Programming in C · Scope, Lifetime & Storage Classes · Full GATE CSE 2016 Set 1 paper

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

Scope, Lifetime & Storage Classes

Question 35, GATE 2016: Find the printed sequence for count(3), where:
void count(int n){static int d=1;printf("%d ",n);printf("%d ",d);d++;if(n>1)count(n−1);printf("%d ",d);}
A:3 1 2 2 1 3 4 4 4. B:3 1 2 1 1 1 2 2 2. C:3 1 2 2 1 3 4. D:3 1 2 1 1 1 2.
The printed main wrapper calls count(3); assume the usual printing declarations.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step through it (7 steps)

The static d is shared across recursive calls. Entry pairs are(3, 1),(2, 2),(1, 3); after the third increment d=4. Each of the three returning frames then prints 4. The complete sequence is 3 1 2 2 1 3 4 4 4, A. The snippet assumes normal printf declarations and acceptance of its void-main wrapper.

There is one static storage cell for d, not one copy per recursion frame. Trace entry: count(3) prints 3,1 and increments to 2; count(2) prints 2,2 and increments to 3; count(1) prints 1,3 and increments to 4. The base call skips recursion but still executes its final print. Returning callers also execute that final print and see the same shared 4. No decrement or new initialization happens during unwinding, which explains all three trailing 4s.

Original paper, page 14 · Answer key