edited by
15,313 views
44 votes
44 votes

 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$
edited by

11 Answers

3 votes
3 votes
Concept:- Static variable never reinitialize

and its lifetime is throughout the program.

Step1:- count(3)

print 3,1

d++;(d=2)

Push d into Stack before jumping count(2)

Step2:-count(2)

print 2,2

d++; (d=3)

Push d into Stack before jumping count(1)

Step3:-Count(1)

Print 1,3

d++; (d=4)

Print d means 4

Now d have been pushed two times into stack now they will pop and print 4 two times

Here d is static variable so latest value will be printed while poping if it is auto variable then we must have to print the value of d at the time we pushed it.

So finally the o/p is

Option A. 3 1 2 2 1 3 4 4 4
2 votes
2 votes
answer is A.bocoz d is static so it has one reference and finally d  value is printed
2 votes
2 votes

count(3): 3  1   d=2   count(2): 2  2   d=3   count(1): 1  3   d=4      (now print final value of d  3 times)   4  4  4

finally: 3 1  2  2  1  3  4  4  4

why: however the previous values of d(in activation stack) are 2, 3 and 4 but last three values of d will print only 4  4  4 beacause d is static and all other values are overwritten by 4 finally in last count().

edited by
Answer:

Related questions