Skip to content
Official PYQ · 2016

GATE CS 2016 Set 1 Q35 — Programming in C

Explain with AI

 What will be the output of the following CC 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);
}
Choose one option
View worked solution

Answer: A

To find the output of the program, we need to trace the execution of count(3). Note that d is a static variable, which means it is initialized only once (at the start of the program) and retains its value across all recursive function calls.

Step-by-Step Trace:

  1. First Call: count(3) (where n=3n = 3)
    • d is initialized to 11.
    • Prints nn and dd: 3 and 1.
      Current Output: 31
    • Increments d to 22.
    • Since n>1n > 1 (3>13 > 1), it calls count(2).
  2. Second Call: count(2) (where n=2n = 2)
    • d is currently 22.
    • Prints nn and dd: 2 and 2.
      Current Output: 3122
    • Increments d to 33.
    • Since n>1n > 1 (2>12 > 1), it calls count(1).
  3. Third Call: count(1) (where n=1n = 1)
    • d is currently 33.
    • Prints nn and dd: 1 and 3.
      Current Output: 312213
    • Increments d to 44.
    • Since n>1n > 1 (1>11 > 1) is false, it skips the recursive call.
    • Prints d: 4.
      Current Output: 3122134
    • count(1) finishes and returns to count(2).
  4. Resuming count(2)
    • Prints d: Since d is static and currently 44, it prints 4.
      Current Output: 31221344
    • count(2) finishes and returns to count(3).
  5. Resuming count(3)
    • Prints d: Since d is static and currently 44, it prints 4.
      Current Output: 312213444
    • count(3) finishes.

Thus, the final output is 3 1 2 2 1 3 4 4 4.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions