GeekInterview.com
Series: Subject: Topic:
Question: 203 of 587

#include
void 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
Asked by: sudamadhuri | Member Since Jul-2007 | Asked on: Aug 7th, 2007

View all questions by sudamadhuri

Showing Answers 1 - 4 of 4 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.

Yes  1 User has rated as useful.
  
Login to rate this answer.

There is no output will be displayed as control doesn,t reach at printf() statement, everytime the value of n is decremented and control trasfered to the begging of the fun() function when n reaches at 0 the condition is false and control trasfered to outside of the if block . so there is output.

  
Login to rate this answer.
jintojos

Answered On : Jul 2nd, 2008

View all answers by jintojos

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..............  

  
Login to rate this answer.
coolquasar

Answered On : Sep 15th, 2008

View all answers by coolquasar

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...

Yes  1 User has rated as useful.
  
Login to rate this answer.

Give your answer:

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

Related Open Questions

Ads

Connect

twitter fb Linkedin GPlus RSS

Ads

Interview Question

 Ask Interview Question?

 

Latest Questions

Interview & Career Tips

Get invaluable Interview and Career Tips delivered directly to your inbox. Get your news alert set up today, Once you confirm your Email subscription, you will be able to download Job Inteview Questions Ebook . Please contact me if you there is any issue with the download.