-6

I have a user defined function that returns the factorial of the number entered. Here is the function:

int factorial_calc(int m1)
{
if(m1==1)
{
 return 1;
}else 
return m1*factorial_calc(m1-1);
}

Now the program works and there seems to be nothing wrong with the program.

What I am asking for here is can someone explain how the code calculates the factorial and gives us the output?

Thanks for all your help! -Sayan. EDIT: Sorry in my hurry I didn't check what I had typed. I corrected it now. Both are factorial_calc now.

Double EDIT: What I really want to know is not about recursion. I know that when the code works (example: let's say m1=5) then it takes 5 and stores it in the variable present in main(). And then does it over and over again till it reaches 0. What I want to know is how does it know that each of the values are going to be multiplied? We only store values in the variables, not math operators. So, what am I missing??

returnNULL
  • 19
  • 6

1 Answers1

1

Recursion: simplify the problem, solve the simpler one

Example: the multiplication of all the numbers from N to 1
1 * 2 * 3 * 4 * 5 * 6 * ... * N

Simplification: the multiplication of all the numbers from N to 1 is N multiplied by the multiplication of all the numbers from N - 1 to 1 which is simpler than the example
N * 1 * 2 * 3 * 4 * 5 * 6 * ... * (N-1)

in pseudo-code

factorial(N) = N * factorial(N - 1)

but with the simplest case in code

if (N == 1) return 1;

Put these statements in a function and you have the solution.

pmg
  • 106,608
  • 13
  • 126
  • 198