Recursions

Hey guys please help me i dont understand how recursion works.
i understand that
5!
5*4
4*3
3*2
2*1
and then it returns the value of 1
and then starts back up again
i got confuse because

2*1=2 right??
3*2=6
4*3=12
5*4=20
my question is how did it generate a 120 out of this numbers


int main()
{
cout<<factorial(5);
}
int factorial(int x)
{
if(x==1) return 1;
else return x*factorial(x-1);
}
Last edited on
What happens is that it multiplies x by whatever value is calculated by factorial(x-1). Which, at (x-x+1) will be 1. So what happens code-wise is, for 5:

5*(4*(3*(2*(1))))

Because each one calls factorial yet again. The inner-most would be calculated first and then work outwards, like this:

x*factorial(x-1) = x*(x-1)*factorial(x-2) = x*(x-1)*(x-2)*factorial(x-3)...
so 2*1=2*3=6*4=24*5= 120 is this how it works?
Last edited on
Yes.
Topic archived. No new replies allowed.