![]() |
|
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
Understanding Recursion
I'm trying to understand the classic compute the factorial of a number business using recursion. Let's say I want to compute the factorial of 4 so in my main function I have something like this:
int x = 4; cout << factorial(x); Then my function definition goes like this: int factorial(int number)
{
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}I guess the way I got it figured so far is this. The value of x which is 4 gets passed to number. Then we have a succession of function calls like this: return 4 * factorial(3) return 3 * factorial(2) return 3 * factorial(1) And I think then that would be all. But it's hard to see the intermediate results with all these successive function calls. One of my books does recommend putting in a statement that would print the level at which each call is and what the intermediate result is. In order for me to do that, would I just do this? else cout << n * factorial(n - 1) Let me know what the best way to understand this is. |
|
|
|
| Bookmarks |
| < |