edited by
15,318 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

Best answer
60 votes
60 votes

Here, d is Static, so the value of d will persists between the function calls.

  1.  $\text{count(3)}$ will print the value of $n$ and $d$ and increments $d$ and call $\text{count(2)} \Rightarrow \text{prints} \ 3 \ 1$.
  2.  $\text{count(2)}$ will print the value of $n$ and $d$ and increments $d$ and call $\text{count(1)} \Rightarrow \text{prints} \ 2 \ 2$.
  3.  $\text{count(1)}$ will print the value of $n$ and $d$ and increments $d  \Rightarrow \ \text{prints} \ 1 \ 3$.

Now, it will return and prints the final incremented value of $d$ which is $4$, three times.
So, option (A) is correct $= 3 \ 1 \ 2 \ 2 \ 1 \ 3 \ 4 \ 4 \ 4$

edited by
23 votes
23 votes

A static local variable is different from a local variable as a static local variable is initialized only once no matter how many times the function in which it resides is called and its value is retained and accessible through many calls to the function in which it is declared.

If a variable is declared static in a function, the same variable/same copy will be used for all recursive calls of that function.

Static variables are allocated memory in the data segment, not stack segment. In this case, d is initialized explicitly so it will be stored in initialized data segment.

Check this - http://www.geeksforgeeks.org/memory-layout-of-c-program/

here count(3) will do 3 things  - prints 31, increments d and call count(2)

count(2) - print 22, increments d and call count(1)

count(1) -  print 13, increments d. Now as 0 $\ngtr 1$ , of it will print final value of d i.e 4 and returns to count(2). count(2) will print 4 and returns to count(3), At last count(3) will print 4.

Final output - 312213444

A is the correct answer. 

13 votes
13 votes
(A)  3 1 2 2 1 3 4 4 4
Answer:

Related questions