Sorry to not reply sooner. I must have been very tired when looking over the code, I understand it better now. However, I have a few more questions now. ( I did look at the ibm.com link, but I always find that my questions haven't been answered or the reasoning has flown above my head ).
Firstly, the code seemingly does 2 things at once. Once the program starts and the multiplication begins, does it multiply n * n-1 first or does it call the function first? For example, if we wanted the factorial of 5, would it be 5 * 5-1 first or would that multiplication be put on "hold" until it finishes running through the function loop until it meets the condition of "n == 1"? So simply, would the program do multiplication as it's looping or once it's done looping and has all the numbers needed to multiply? I think the latter cause is the most probable.
Secondly, what stops the function from giving you the answer as "1" for whatever factorial looked for? What I mean is that there's an if function stating that when the variable is less than two, then the function should return 1. But when the function loops, it will always eventually hit one, yet the answer never comes out as "1", why?
Here is my code for factorials after a bit or variable changing to fit my calculator :
1 2 3 4 5 6 7
|
unsigned long long factorial(unsigned int x)
{
if (x < 2) return a = 1;
else return a = x * factorial(x - 1);
}
|
With this code, a is what gets displayed as the answer once the function is done and returns the final solution. The question though is why doesn't the answer come out as 1 even thought the function will always eventually have x<2 which should make the function send out the answer as 1. Moreover, how does it not make the answer always come out as 1 but instead makes the function stop when x = 1 ?
Last Question : When typing in a negative number, the console will freak out. For example -5! will not compute. How come it doesn't give an answer of 1? - Even though there's an if function saying if x > 1 then a = 1 ? Thanks for all the help.