Figure 6.27 uses recursion to calculate and print the factorials of the integers 0–10. (The choice of the data type unsigned long
is explained momentarily.) The recursive function factorial
(lines 18–24) first determines whether the terminating condition number <= 1
(line 20) is true. If number
is less than or equal to 1, the factorial
function returns 1 (line 21), no further recursion is necessary and the function terminates. If number
is greater than 1, line 23 expresses the problem as the product of number
and a recursive call to factorial
evaluating the factorial of number - 1
, which is a slightly simpler problem than the original calculation factorial (number)
.
1 // Fig. 6.27: fig06_27.cpp
2 // Recursive function factorial.
3 #include <iostream>
4 #include <iomanip>
5 using namespace std;
6
7 unsigned long factorial( unsigned long ); // function prototype
8
9 int main()
10 {
11 // calculate the factorials of 0 through 10
12 for ( unsigned int counter = 0; counter <= 10; ++counter )
13 cout << setw( 2 ) << counter << "! = " << factorial( counter )
14 << endl;
15 } // end main
16
17 // recursive definition of function factorial
18 unsigned long factorial( unsigned long number )
19 {
20 if ( number <= 1 ) // test for base case
21 return 1; // base cases: 0! = 1 and 1! = 1
22 else // recursion step
23 return number * factorial( number - 1 );
24 } // end function factorial
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
3.147.53.166