What will be the output of the following C program? void count(int n){ static int d=1; printf("%d ", n); printf("%d ", d); d++; if(n>1) count(n-1); printf("%d ", d); } void main(){ count(3); }
Topic-wise GATE CS PYQs with verified steps
GATE CSE 2016 Set 1 · Q35
Time
void count(int n){
static int d=1;
printf("%d ", n);
printf("%d ", d);
d++;
if(n>1) count(n-1);
printf("%d ", d);
}
void main(){
count(3);
}Select one answerSingle correct
Solution
Official answer: A) 3 1 2 2 1 3 4 4 4
RecursionThe variable d is declared as static int d = 1;, so it is initialized once and retains its value across recursive calls.
Let's trace the execution of count(3):
count(3) called:
Prints n (which is 3) and d (which is 1). Output so far: 3 1
d is incremented to 2.
Since (), it calls count(2).
count(2) called:
Prints n (which is 2) and d (which is 2). Output so far: 3 1 2 2
d is incremented to 3.
Since (), it calls count(1).
count(1) called:
Prints n (which is 1) and d (which is 3). Output so far: 3 1 2 2 1 3
d is incremented to 4.
Since () is false, it does not make another recursive call.
Prints d (which is 4). Output so far: 3 1 2 2 1 3 4
count(1) returns to count(2).
Returning through the recursion stack:
In count(2): prints d (which is 4). Output so far: 3 1 2 2 1 3 4 4
count(2) returns to count(3).
In count(3): prints d (which is 4). Output so far: 3 1 2 2 1 3 4 4 4
Thus, the complete output is 3 1 2 2 1 3 4 4 4, which matches option (A).
Try the question first, then check your work.
Examiner trap
Remember that a static variable is initialized only once and retains its updated value across all recursive calls and returns.
This Recursion previous year question is Q35 of the GATE CSE 2016 Set 1 paper. Find more GATE CSE PYQs on Recursion in Programming and Data Structures, or browse all GATE CSE PYQs.
Free diagnostic
Take the 20-minute diagnostic: the 3 topics that cost you the most marks, and a rank range. Or sit 5 related Recursion PYQs now with no account.
An official question by email at 7 AM IST, with a link to its verified solution. Unsubscribe in one click.
Recursion has 19 GATE CSE PYQs across 15 papers from 2011 to 2026. 10 of them are 2-mark MCQs like this one, and it is the only one in GATE CSE 2016 Set 1.
How GATE tests RecursionIndependent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.