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

## 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));
}

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

Thomas

Edited by Thomas Wiborg

##### Share on other sites

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

Edited by Thomas Wiborg

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

• 11
• 9
• 17
• 13
• 11