#includevoid fun(int);void main(){ inta; a=3; fun(a); }void fun(int){ if(n>0) { fun(--n); printf("%d",n); fun(--n); } } What is the output of the above program? Explain.

0 1 2 0

Questions by sudamadhuri

Showing Answers 1 - 12 of 12 Answers

The Output of the above program would be 0,1,2,0.

Explanation : the n value is getting decremented as 2,1,0. based on the condition if(n>0) when it reaches the printf the 0,1,2,0 values are getting printed.
it is working on recursive manner.

jintojos

  • Jul 2nd, 2008
 

The out will be just like 3 2 1 0 2 1 0 1 0 0... not sure
This is a recursive function with 2 recursive calls one at line 13 and other in at line 15.
The variable 'a' initialized to 3 and is passed to the function fun(), then the local variable 'n' in the fun() will contains the value 3. The second step in the function fun() is an recursive call so it stores its local variable 'n' into stack.ie in the first call it stores 3 and second call 2 and then 1.When 'n' equal to 0 it returns functions one by one and pop the value from stack to the local variable.The next statement after the funtion call is printf() statement and will print the value of local variable and then the  next recursive call made and so on..............  

  Was this answer useful?  Yes

coolquasar

  • Sep 15th, 2008
 

It proceeds like this

fun(3)

fun(2)

fun(1)

fun(0)

fun(-1)

printf("%d",n)(Here n is 0)

fun(-1)

printf("%d",n)(Here n is 1)

fun(0)

printf("%d",n)(Here n is 2)

fun(1)

fun(0)

printf("%d",n)(Here n is 0)

fun(-1)

Return to main function...

i can explain it better if there was a virtual pen n paper...

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions