Recursion doubt:-

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vensriram
    New Member
    • Aug 2010
    • 48

    #1

    Recursion doubt:-

    Code:
    {
     int a;
     a=3;
     fun(a);
      system("PAUSE");	
      return 0;
    }
    void fun(int n)
    {
         if (n>0)
         {
                 fun(--n);
                 printf("%d",n);
                 fun(--n);
                 }
                 }
    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
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    which loop?

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      2. if checks 3>0 since it is true control goes inside the loop
      Which loop?

      Comment

      • vensriram
        New Member
        • Aug 2010
        • 48

        #4
        The IF loop that is inside the function FUN.That loop has the call for the function FUN again....

        Comment

        • vensriram
          New Member
          • Aug 2010
          • 48

          #5
          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

          Comment

          • MartijnHoekstra
            New Member
            • Sep 2010
            • 39

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

            Comment

            Working...