Sign in to follow this  
Thomas Wiborg

How C# computes Recursion

Recommended Posts

Thomas Wiborg    1573

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
Alpha_ProgDes    6921

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this