In the tut example below I cannot understand why "a" is reduced by 1 everytime "factorial" is called. It looks like to me if "a" was originally 5 then it would always be 5 because I don't see anything that sets a--.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
elsereturn (1);
}
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
return 0;
}
It's because it doesn't actually do that...If you are using a debugger and stepping through it, then the 'a' you are talking about is the parameter a, not the actual 'a'.
Fellas I'm sorry I keep hounding this but I've gotten over to structs and realized I'm pretty much lost. So I'm wading back thru the tuts trying to get a better understanding of what's happening.
I kinda, sorta understand what you are saying. Maybe I need to set CodeBlocks up so I can use the debugger. I know it is returning (a-1) every time, It is just not really clear to me from the code, why that is happening. Anyway, both of you thanks.
a * factorial (a - 1) which if you continue to expand it becomes:
a* (a - 1) * (a - 2) * (a - 3) ... since it is calling itself...until it reaches a = 1, then all the functions start returning until you get the answer:
f# is what the function is returning
f1(a * f2(a-1 * f3(a -2)))
When I first read Zhuge's explanation I replaced the word 'factorial' with the word 'junk' in the program thinking that just maybe the word 'factorial' meant this, a* (a - 1) * (a - 2) * (a - 3)... in C++.
The new version of the program worked just fine. I'm thinking now that this statement:
(a * factorial (a-1))
will always mean a*(a-1) * (a-2) * (a-3).....regardless of what is used for the function name.
Actually, I don't think that's what it means. I've never used it but looking at the function, I'm assuming if you have like say the number 6.
Your function will be (6 * factorial (6-1)) = (6 * factorial (5))
From what Zhuge said factorial (5) is 5 * factorial (4)
then factorial (4) = 4 * factorial (3) ...
So you will end up with 6 * factorial (5) which is equivalent to 6 * 5 * factorial (4) which again is equivalent to 6 * 5 * 4 * factorial(3) so on and so forth.
Makes sense?
What you're doing is think of factorial like you learn it in math, you would be correct to say a! = a*(a-1) * (a-2) * (a-3) * ... * 1 in a math class. But this factorial is different from the factorial "!" of math. Think of it like Zhuge said: "a recursive function so it calls itself with the parameter (a - 1)."
Yep fellas it all makes sense. I understand what factoring a number is. I just don't understand why when looking at the code. It seems me and Mr. C++ has a failure to communicate. :)
I really appreciate all your posts trying to make me understand but it looks like it is time to move on and hope I can work around any problem I encounter with this.