using recursion for factorial function

Jul 29, 2013 at 11:37pm
Hey, im new to the forum and c++ over all, i have been studying for about 2 months and currently im making a calculator with a bunch of different functions(beginner stuff), if anyone remembers form math factorial is shown as 5! which means 5X4X3X2X1 = 120, now i have been watching a video where it shows a example of how to do this, my problem is i do not understand the following code.

int fact(int x){
if(x==1){
return x;
}
else{
return x*fact(x-1);
}
}
this code works perfectly fine, what i dont understand is, if you call the function with int of 5, the first step is to check if x==1, it is not so it will return 5*fact(5-1) which is 20, when it returns 20, it wont be equal to 1, so 20*fact(20-1) is 19, but that is not how it works, im very confused by this, can someone explain me how this works
Edit: also if by the time the factorial reaches 1, it returns x which =1, then how is it 120
Last edited on Jul 29, 2013 at 11:39pm
Jul 29, 2013 at 11:55pm
Let's say you call fact(5), something like this would happen:

5 is not equal to 1 so return 5*fact(5-1)
5-1 = 4 and 4 is not equal to 1 so return 4*fact(4-1)
4-1 = 3 and 3 is not equal to 1 so return 3*fact(3-1)
3-1 = 2 and 2 is not equal to 1 so return 2*fact(2-1)
2-1 = 1 and 1 is equal to 1 so return 1

That returned 1 is sent to 2*fact(2-1) which becomes 2*1 and returns 2
That returned 2 is sent to 3*fact(3-1) which becomes 3*2 and returns 6
That returned 6 is sent to 4*fact(4-1) which becomes 4*6 and returns 24
That returned 24 is sent to 5*fact(5-1) which becomes 5*24 and returns 120
That returned 120 is the final answer

Hope this helped you better understand the function
Jul 30, 2013 at 12:07am
And where would the returns be saved, once it returns the first number which is 5*fact(5-1) , it would be equal to 20 right?, where is that 20 saved and how does the program know to calculate 4 afterwards if the return was 20
EDIT: Never mind, after the 5th time reading that i understood, thanks for the reply!!
Last edited on Jul 30, 2013 at 12:08am
Topic archived. No new replies allowed.