Hey all. I'm slowly chugging through the tutorials on this website and I hit a snag at the factorial calculator:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// factorial calculator
#include <iostream>
using namespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
return 0;
}
|
After working out how the loops work to produce an answer, I wondered where this answer (I used three because it was easy to write on paper while working), was stored. Then what
return(1);
does with the answer.
I experimented with checking the values of
a
during the looping: 3, 2, 1 (For number = 3). So six isn't stored there. I eventually came to the conclusion that the number is just returned from the function is stored in
function
. But I don't see how this is right.
Then I fiddled with
return (1);
and found out that the value in the parenthesis was directly related to the answer. The return value (r) was a multiplier for the recursion answer (x) and totaled to a new answer,
factorial (number)
(y).
1 2 3 4 5
|
r x y
0 * 6 = 0
1 * 6 = 6
2 * 6 = 12
3 * 6 = 18
|
Since the tutorial didn't cover return in any real depth, especially
return (1);
(up to where I am and where I read up to, but got confused going too far), I'd like to know how this changes the end result. Looking around the net I find that the return value is something to do with errors. But.. I don't see how this applies here.
In short:
Where is the answer stored after recursion calculation?
In
return (1)
how is value able to effect the results?
Thanks