Sams Teach Yourself C in 21 Days

(singke) #1
Packaging Code in Functions 117

5


However, you can also calculate x!like this:
x! = x * (x-1)!
Going one step further, you can calculate (x-1)!using the same procedure:
(x-1)! = (x-1) * (x-2)!
You continue calculating recursively until you’re down to a value of 1 , in which case
you’re finished. The program in Listing 5.5 uses a recursive function to calculate factori-
als. Because the program uses unsignedintegers, it’s limited to an input value of 8 ; the
factorial of 9 and larger values are outside the allowed range for integers.

LISTING5.5 recurse.c. Using a recursive function to calculate factorials
1: /* Demonstrates function recursion. Calculates the */
2: /* factorial of a number. */
3:
4: #include <stdio.h>
5:
6: unsigned int f, x;
7: unsigned int factorial(unsigned int a);
8:
9: int main( void )
10: {
11: puts(“Enter an integer value between 1 and 8: “);
12: scanf(“%d”, &x);
13:
14: if( x > 8 || x < 1)
15: {
16: printf(“Only values from 1 to 8 are acceptable!”);
17: }
18: else
19: {
20: f = factorial(x);
21: printf(“%u factorial equals %u\n”, x, f);
22: }
23:
24: return 0;
25: }
26:
27: unsigned int factorial(unsigned int a)
28: {
29: if (a == 1)
30: return 1;
31: else
32: {
33: a *= factorial(a-1);
34: return a;
35: }
36: }

09 448201x-CH05 8/13/02 11:15 AM Page 117

Free download pdf