# recurive function cannot understand one line plz have a look

• 04-16-2004
blackgold>>
recurive function cannot understand one line plz have a look
Code:

```//recursive factorial function #include <iostream> #include <iomanip> using namespace std; unsigned long factorial( unsigned long ); int main() {   for (int i = 1; i <= 10; i++ )       cout << setw( 2 ) << i << "! = " << factorial( i ) << endl; // this part <<factorial(i)  calls function factorial with the parameter of i?   return 0; } // recursive definition of function factorial unsigned long factorial( unsigned long number ) {   if ( number <= 1 )  // base case       return 1;   else                // recursive case       return number * factorial( number -1 );  //this part here i have problem also number* factorial(number-1 ,so what happens here factorial has no value? so why multiply by number? i'm lost please help. }```
• 04-16-2004
noob2c
paramenter i, in that loop u set i to 1 and loop till it reaches 10. So whenever u have the call as factorial(i) ..... the present value of i is sent down to the function.

okay here is a test case that will help you understand the function ( im guessing thats what ur having trouble with )

lets assume i = 5 when the function is called.

so it goes through the check and since 5 is greater than 1 it goes to the next step that is the recursice call.

so now in reality things look like 5*factorial(4)
it will go through the steps like till it hits 1, and will look something like this on the stack

5*4*factorial(3) //second call
5*4*3*factorial(2)//third call
5*4**3*2*factorial(1)
now it will return 1 and things will start to unwind and will go on multiplying.
5*4*3*2*1 == 120

• 04-16-2004
jlou
Quote:

so what happens here factorial has no value?
factorial always returns a value, so you are multiplying number * the value returned by the function call. The fact that it is the same function is irrelevant, because each call is separate.
Code:

```unsigned long square( unsigned long number ) {     return number * number; } unsigned long myFunc( unsigned long number ) {     return number * square( number - 1 ); }```
The code in myFunc follows the same idea, multiply a number by the result of a function. Even though it is not recursive, it works the same as your recursive one.
• 04-17-2004
blackgold>>
Guys thank you so much i understand now how this works.
Thanks alot !