can someone please explain this factorial function

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;


	}
Last edited on
n==4.

Lets evaluate the if out form the code. The factorial(4) essentially computes same as:
1
2
3
4
int factorial( int n )
{
  return factorial(n - 1) * n;
}

We know that n==4. The value returned is thus:
factorial(3) * 4

What does factorial(3) return?
factorial(2) * 3

What does factorial(2) return?
factorial(1) * 2

What does factorial(1) return? Here the if takes the other branch:
1

Lets go back to the factorial(2) now that we know the true value of factorial(1). Substituting that value means that factorial(2) returns:
1 * 2 (==2)

Lets go back to the factorial(3) now that we know the true value of factorial(2):
2 * 3 (==6)

Lets go back to the factorial(4) now that we know the true value of factorial(3):
6 * 4 (==24)
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.
Topic archived. No new replies allowed.