Programming in C

(Barry) #1

160 Chapter 8 Working with Functions


unsigned long int factorial (unsigned int n)
{
unsigned long int result;

if ( n == 0 )
result = 1;
else
result = n * factorial (n - 1);

return result;
}

Program 8.16 Output
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

The fact that the factorialfunction includes a call to itself makes this function recur-
sive.When the function is called to calculate the factorial of 3, the value of the formal
parameter nis set to 3 .Because this value is not zero, the following program statement
result = n * factorial (n - 1);
is executed, which, given the value of n, is evaluated as
result = 3 * factorial (2);
This expression specifies that the factorialfunction is to be called, this time to calcu-
late the factorial of 2.Therefore, the multiplication of 3 by this value is left pending
while factorial (2)is calculated.
Even though you are again calling the same function, you should conceptualize this as
a call to a separate function. Each time any function is called in C—be it recursive or
not—the function gets its own set of local variables and formal parameters with which
to work.Therefore, the local variable resultand the formal parameter nthat exist when
the factorialfunction is called to calculate the factorial of 3 are distinct from the vari-
able resultand the parameter nwhen the function is called to calculate the factorial
of 2.

Program 8.16 Continued
Free download pdf