Recursivity tutorial

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
The result of the inner call of the function is used in the outer call of the function
factorial (3) calls factorial (3-1) ( factorial (2) )
which calls factorial (2-1) ( factorial (1) )
in factorial (1) a is equal to one so 1 is returned
1
2
3
4
if (a > 1)
   return (a * factorial (a-1));
else
   return (1);


factorial(3) = 3 * factorial ( 2 * factorial ( 1 ) ) = 3 * factorial ( 2 * 1 return (1); )
Last edited on
Right, it sounds like you are trying to follow the calls themselves in order rather than the returns. The "unwrapping" of the calls is how the answer comes together.
Thanks Bazzy and seymore15074 for your feedback.

So according to you Bazzy, after doing the equation to get the answer of 6, it then continues multiplying the existing equation with anything else in it's 'path'; which is the return(1);. Thanks for clearing that up!

And thanks seymore15074 making me stop over thinking the issue and to just think of it in a more linear way.

Thanks heaps!

Check this tutorial: http://simpleprogrammingtutorials.com/tutorials/concepts/recursion.php It shows calculation of the 3! step by step. It may make things clearer.
Topic archived. No new replies allowed.