Hey guys i have a question about recursion im trying to learn it and i got stuck in the point where it hits the base case .
[code]
int factorial(int x)
{
if(x==1) return 1;
else return x*factorial(x-1);
}
5*4=20
4*3=12
3*2=6
2*1=2
and then it returns the value 1 and starts its way back up.
but how it work
// Once this function ends, it will return the value 1 if the value passed was 1 or higher
int factorial(int x)
{
if(x==1) // 20 is not 1, 2nd time its 19, 3rd time it is 18 and so on
return 1; // until the function stops calling itself and returns the value 1
elsereturn factorial(x-1); // so it takes 1 away from x, and with that value it calls itself
}
int main()
{
cout << factorial(20) << endl; // factorial is called with the value 20, this prints 1
return 0;
}