By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,984 Members | 2,615 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,984 IT Pros & Developers. It's quick & easy.

Recursion doubt:-

P: 48
Expand|Select|Wrap|Line Numbers
  1. {
  2.  int a;
  3.  a=3;
  4.  fun(a);
  5.   system("PAUSE");    
  6.   return 0;
  7. }
  8. void fun(int n)
  9. {
  10.      if (n>0)
  11.      {
  12.              fun(--n);
  13.              printf("%d",n);
  14.              fun(--n);
  15.              }
  16.              }
What does this program prints....
1. At first 3 is passed to fun
2. if checks 3>0 since it is true control goes inside the loop
3. In the loop again fun(==3) so fun(2), again if(2>0).
4. Likewise if(0>0) will be false and atlast the program will not print anything.

But my compiler provides the answer as 0120

Kindly provide the clarification. Thanks in advance
Sep 2 '10 #1
Share this Question
Share on Google+
5 Replies

P: 542
which loop?
Sep 2 '10 #2

P: 542
2. if checks 3>0 since it is true control goes inside the loop
Which loop?
Sep 2 '10 #3

P: 48
The IF loop that is inside the function FUN.That loop has the call for the function FUN again....
Sep 2 '10 #4

P: 48
Yes it goes inside the loop. But again there is a function call inside the loop fun(--n); so this interprets in to fun(2). So this is a recursive call so the control again goes to the start of the function fun() so again it it checks if(2>0) and again since it is true it goes inside the loop. Again the same thing continues until IG(0>0) is encountered. now the if becomes false and hence the control should exit.
Hence it should not print anyhing. But it prints 0120.
Kindly clarify
Sep 2 '10 #5

P: 39
First of, it is called an IF statement.
Loops are 'while' or 'for'.

Your clarification started correctly, firstly you call fun(3). which imediatly calls fun(2) -> fun(1) then fun(0).
The last one fun(0), doesnt do anything.
so now it goes back to where it called fun(0).. below there is the printf..
You forgot that part.
Also remember, every time fun is called, a new 'n' is created for every 'call stack'. So when coming back to previous call, the n has different value.
Sep 2 '10 #6

Post your reply

Sign in to post your reply or Sign up for a free account.