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