GATE 2016 CS – Question 45
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);
}Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: (A) 3 1 2 2 1 3 4 4 4
Explanation
The variable `d` is static, so all the calls share one copy. `count(3)` prints 3 and 1, then sets `d` to 2. `count(2)` prints 2 and 2, then sets `d` to 3. `count(1)` prints 1 and 3, then sets `d` to 4 and does not recurse. Then each of the three calls prints the final value 4 as it returns. The output is 3 1 2 2 1 3 4 4 4.