To illustrate the differences between iteration and recursion, let’s examine an iterative solution to the factorial problem (Fig. 6.30). A repetition statement is used (lines 23–24 of Fig. 6.30) rather than the selection statement of the recursive solution (lines 20–23 of Fig. 6.27). Both solutions use a termination test. In the recursive solution, line 20 (Fig. 6.27) tests for the base case. In the iterative solution, line 23 (Fig. 6.30) tests the loop-continuation condition—if the test fails, the loop terminates. Finally, instead of producing simpler versions of the original problem, the iterative solution uses a counter that is modified until the loop-continuation condition becomes false.
1 // Fig. 6.30: fig06_30.cpp
2 // Iterative function factorial.
3 #include <iostream>
4 #include <iomanip>
5 using namespace std;
6
7 unsigned long factorial( unsigned int ); // 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 // iterative function factorial
18 unsigned long factorial( unsigned int number )
19 {
20 unsigned long result = 1;
21
22 // iterative factorial calculation
23 for ( unsigned int i = number; i >= 1; --i )
24 result *= i;
25
26 return result;
27 } // 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
18.117.100.20