For the life of me I cannot visualize how the program is computing the factorial, I of course understand the method, but I'm just struggling to see how the new value of n, when implemented back into the function factorial, leads to the factorial, i.e n = 4, and somehow computes to 4x3x2x1 from this function. My understanding is that when n =4, it is subtracted by 1, and multipled by the new value, 3. This 3 value is then ran through the function again until value of 1 is reached I just can't see how this = 4x3x2x1. I'm sure it has something to do with the return value, but I just cannot see it, given that result = factorial(n-1)*n, what is the value of factorial(n-1)...? I think I am probably over complicating things, but I really want to know the answer.
1 2 3 4 5 6 7 8 9 10 11
int factorial(int n)
{
int result;
if (n == 1)
result = 1;
else
result = (factorial(n - 1)*n);
return result;
}
I was just stuck up on the whole calling the factorial function again, rather than it just being n*n-1, but I now realise that this is essential to ensure n stops at == 1. Thank you for the clear answer, it makes it very easy to understand.