Here we are going to walk through an example of recursion using the factorial function. The Factorial of a number is the product of the series that starts with the number and decreases by one each time. In math notation that is
1! = 1So 3! is 3 * 2 * 1 = 6.
n! = n * (n-1)!
An efficient way to calculate this on the computer is
int
fact(int n)
{
int f = 1;
while(n > 1)
f = f * n--;
return fl;
} // fact
while this is fast, it doesn't look like the definition of the problem. The problem is defined in terms of itself since n! = n * (n-1)!. Since the definition is recursive, it makes the code easier to follow if it is recursive as well. Like this:
int
factr(int n)
{
if(n == 1) return 1;
int r = factr(n-1);
int x = n * r;
return x;
} // factr
Let's walk through the execution of this bit of code. Remember that each time a function is called a new set of local variables and parameters is created.