Machine-translated by Google. Questions are authored in English.
Top

Discussion

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\(\gt\)1) count(n-1);
    printf("%d ", d);
}

void main(){
    count(3);
}

  • 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

Answer: A

The output is 3 1 2 2 1 3 4 4 4.

The key is that d is static: there is one copy shared by every call, initialized once and never reset.

  1. count(3) prints 3 and d = 1, then d becomes 2, and calls count(2).
  2. count(2) prints 2 and d = 2, then d becomes 3, and calls count(1).
  3. count(1) prints 1 and d = 3, then d becomes 4; since n is not greater than 1 it does not recurse, and prints d = 4.
  4. Back in count(2), it prints d, now 4; back in count(3), it prints d, 4.

So the sequence is 3 1, 2 2, 1 3, then 4 4 4. Treating d as an ordinary local variable, reset to 1 in each call, gives 3 1 2 1 1 1 2 2 2; the seven-number options forget that every call prints d once more as it returns.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.