A recursive function is when you make a function keeps on calling itself in itself to get certain result.
Suppose we put in a 3 in factorial(int n). What will happen? We will have n = 3 in the function factorial.
Now, stick with me a bit. This can be a bit tricky. Think of it as a building. The first time we call a function, we are in first floor of that function. If we call a function once again, we will be in the second floor. Once we finish our business in there, we go back to the first floor. If we also finish business in this floor, we also go back to the previous floor.
Now, let's say the first time we call factorial(int n), we put in 3. Referring to the code above, looks like I have to come down to:
1 2
|
else
return 3*factorial(n-1)+n*factorial(n-2);
|
Now, to avoid some confusion, let's make it more clear:
1 2
|
else
return ( (3*factorial(2)) + (3*factorial(1)) );
|
We have two factorial call in line 25. Now, the program runs and sees that it has to enter the function, so now we go to the 2nd floor with the factorial function. But this time, we have n = 2.
The same thing happens and we hit line 25 once again. So we have to go into the factorial function again, but this time, it's
1 2
|
else
return ( (3*factorial(1)) + (2*factorial(0)) );
|
So here goes our 3rd floor. In our 3rd time, n = 1, so we hit the if statement and return n+1 which is 2. Now, we're done and we can return a value, so we get back to 2nd floor.
Now, we have the result 2 which comes from n+1 so let's put it in here to make it a bit easier:
1 2
|
else
return ( (3*2) + (2*factorial(0)) );
|
We still have factorial(0) on the right, so we go to the 3rd floor again with factorial(0) and that yields 1 and we get back down to the 2nd floor, so now we have:
1 2
|
else
return ( (3*2) + (2*1) );
|
Now, we have the result, so we return to the previous function which is on 1st floor. (3*2) + (2*1) is 8 so let's replace factorial(2) with that.
1 2
|
else
return ( (3*8) + (3*factorial(1)) );
|
On the first floor, we still have factorial(1), so we go on the 2nd floor with factorial(1). Going through the codes, we go into the if statement because n = 1 and it returns 2 and get back to the first floor, so now let's replace factorial(1) with 2:
1 2
|
else
return ( (3*8) + (3*2) );
|
Now, we are on the first floor, we can return the result successfully as all the recursive functions have been called. It's like stacking when you call a function in a program.
If you are still confused, tell me and I will see if I can come up with a better example.