• retagged by
3,502 views

3 Answers

Best answer
5 5 votes
NOTE THAT i is static variable ===> loop must be stop at some where

printf function is called after recursion completed ====> updated value of variable is printed...

updated value = 0 at last step ===> recursion exit

0,0,0,0 as o/p

 

doubt is how many no.of zero's would print?

5--->4--->3--->2--->1

at i=1, if condition makes it 0 and evaluate as false ===> when i=1, print statement doesn't executed...

therefore only four number of zero's should print.
• selected by
4 4 votes

Using tree method, go top to down left to right, print value of i whenever printf(i) encountered

1 1 vote

You can understand more clearly using two basic concepts.

First, Static variable assign memory only once in the entire execution of a program, unlike local variable can have a reference of more than one memory after each local declaration.

Second, Visually the recursion call stored activation record in a stack.

Thing going like that:

Let the declaration of a static variable is line number 1 and accordingly other follow line number.

In each call function run only up to line number 3 and store its state in stack activation record and static value reduce its value continuously (4,3,2,1) at i=0, the condition will fail. After line number 3, the execution of other state stored in stack execute started and get the value of i=0 at each time.

There is four activation record in the stack for i=4,3,2,1 so 4 zeros print consecutively.

If this program is tail recursive, it need not store the state in stack and value print (4,3,2,1) if you call main after printf 

If you know stack and how the activation record stored in a stack then you can visualize my explanation easily. 

If anyone feels anything wrong, pls comment.

Thanks!

 

Position:
Show:

Related questions

0 0 votes
2 answers 2 answers
1.5k
1.5k views
Rustam Ali asked Sep 3, 2018
1,477 views
Find time complexity of below Program?A(n){if(n<=1) return;elsereturn $A(\sqrt{n})$ ;}
8 8 votes
3 3 answers
412
412 views
GO Classes asked Jun 17
412 views
What is the output of the following code?#include <stdio.h void update(int n, int *p) { if (n <= 0) return; *p = *p + n; update(n - 2, p); *p = *p + n; } int main() { int...
6 6 votes
2 2 answers
344
344 views
GO Classes asked Jun 17
344 views
What is the output of the following code?#include <stdio.h int fun(int n) { int x = n; if (n <= 0) return 0; x = x + 2; return x + fun(n - 2); } int main() { printf("%d",...
6 6 votes
2 2 answers
373
373 views
GO Classes asked Jun 17
373 views
How many times is $\texttt{fun()}$ called when the following code is executed? (Count the first call also).#include <stdio.h int fun(int n) { if (n <= 1) return 1; return...