Jump to content
  • Advertisement
Sign in to follow this  
Thomas Wiborg

How C# computes Recursion

This topic is 2111 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello guys, I have this set of code
 

class Factorial
    {
        public int Fac(int x)
        {
            if (x == 1)
            {
                return 1;
            }
            else
            {
                return x * Fac(x - 1);
            }
        }
    }


 static void Main(string[] args)
        {
            Factorial fac1 = new Factorial();
            Console.WriteLine(fac1.Fac(4));   
            Console.ReadLine();
        }

The thing is, I know how factorial works. Like 4! = 4*3*2*1 = 24

But i dont see how the computer computes it. The debugging and breakpoints make me more confused. Does anyone have the time to explain me in detail how this works?

One of my way of thinking is:

First iteration:
return x * Fac(x - 1);    = 4 * 3;
Second:
x * Fac(x - 1);              = 3 * 2
Third
x * Fac(x - 1);              = 2 * 1

But nothing returns 24.

Tho I know that in the end the computer does 4*6 = 24

Thanks for all reply!

Thomas

Edited by Thomas Wiborg

Share this post


Link to post
Share on other sites
Advertisement

Thanks alot ADP and Eppo!

And ADP for trying to turn my head around in the right direction, like 100times, lol !

Edited by Thomas Wiborg

Share this post


Link to post
Share on other sites

The TAIL recursion version of factorial

class Factorial
    {
        public int Fac(int x)
        {
             return FacAcc(x, 1);    
        }

        private int FacAcc(int x, int acc)
        {
             if (x == 0 || x == 1) return acc;
             else FacAcc(x - 1, acc * x);
        }
    }
Edited by Alpha_ProgDes

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!