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); } $3 \ 1 \ 2 \ 2 \ 1 \ 3 \ 4 \ 4 \ 4$ $3 \ 1 \ 2 \ 1 \ 1 \ 1 \ 2 \ 2 \ 2$ $3 \ 1 \ 2 \ 2 \ 1 \ 3 \ 4$ $3 \ 1 \ 2 \ 1 \ 1 \ 1 \ 2$ Programming in C gatecse-2016-set1 programming-in-c recursion normal + – Sandeep Singh asked Feb 12, 2016 • edited Jan 24, 2018 by kenzou Sandeep Singh 15.6k views answer comment Share Follow See all 11 Comments See all 11 11 Comments reply Show 8 previous comments Rohit Suryanarayan commented Aug 17, 2018 reply Follow Share No, I think that is not the else part. It is the statement which will execute irrespective of the above if condition. 0 votes 0 votes priyanka manwani commented Dec 14, 2018 reply Follow Share Isn't printf("%d",d); the ELSE part ? if (n>1) count (n-1); <- If condition true printf ("%d",d); <- If condition false Then C will be correct answer. how can we know that ???,,,,,while practicing i also thought it coulb be else part 0 votes 0 votes Satbir commented Aug 6, 2019 reply Follow Share If you look carefully , the program has 3 print statements without any condition. So the outputs generated will be multiple of 3. $\therefore$ Option $c$ and $d$ are eliminated.(as they generate 7 outputs) 2 votes 2 votes Please log in or register to add a comment.
1 votes 1 votes Guys reccursion tree: https://gateoverflow.in/?qa=blob&qa_blobid=11408070808494714478 Bharath_1999 answered Aug 28, 2018 Bharath_1999 comment Share Follow See all 0 reply Please log in or register to add a comment.
0 votes 0 votes D is the static variable so the answer is an option (A) 3 1 2 2 1 3 4 4 4 1. count(3): Print 3 1 d=2,count(2) 2. count(2): print 2 2 d=3,count(1) 3. count(1): print 3 1 Now the condition fails and it will print value 4, for 3 times. ushamya answered Aug 29, 2018 ushamya comment Share Follow See all 0 reply Please log in or register to add a comment.
0 votes 0 votes Answer: option (a) => 312213444 first two prints for count (3) call n=3 d=1 first two prints for count (2) call n=2 d=2 first two prints for count (1) call n=1 d=3 After that it will follow recursion stack to print remaining print statements. Since 'd' is a static variable so value is shared among the recursive calls and it will print the latest updated value of d that is 3 times 4.. d=4 after evaluation of d++ in last recursive call. dexter_n answered Jul 26, 2020 dexter_n comment Share Follow See all 0 reply Please log in or register to add a comment.