The GATE Grind

GATE 2016 CS – Question 45

Programming and Data Structures · Recursion · 2 marks · Multiple choice

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);
}
  1. 3 1 2 2 1 3 4 4 4
  2. 3 1 2 1 1 1 2 2 2
  3. 3 1 2 2 1 3 4
  4. 3 1 2 1 1 1 2

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.