6.21. Recursion vs. Iteration

In the two previous sections, we studied two functions that easily can be implemented recursively or iteratively. This section compares the two approaches and discusses why you might choose one approach over the other in a particular situation.

Both iteration and recursion are based on a control statement: Iteration uses a repetition structure; recursion uses a selection structure. Both iteration and recursion involve repetition: Iteration explicitly uses a repetition structure; recursion achieves repetition through repeated function calls. Iteration and recursion both involve a termination test: Iteration terminates when the loop-continuation condition fails; recursion terminates when a base case is recognized. Iteration with counter-controlled repetition and recursion both gradually approach termination: Iteration modifies a counter until the counter assumes a value that makes the loop-continuation condition fail; recursion produces simpler versions of the original problem until the base case is reached. Both iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false; infinite recursion occurs if the recursion step does not reduce the problem during each recursive call in a manner that converges on the base case.

To illustrate the differences between iteration and recursion, let us examine an iterative solution to the factorial problem (Fig. 6.31). Note that a repetition statement is used (lines 28–29 of Fig. 6.31) rather than the selection statement of the recursive solution (lines 24–27 of Fig. 6.28). Note that both solutions use a termination test. In the recursive solution, line 24 tests for the base case. In the iterative solution, line 28 tests the loop-continuation condition—if the test fails, the loop terminates. Finally, note that 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.

Fig. 6.31. Iterative factorial solution.

 

 1   // Fig. 6.31: fig06_31.cpp
 2   // Testing the iterative factorial function.
 3   #include <iostream>
 4   using std::cout;
 5   using std::endl;
 6
 7   #include <iomanip>
 8   using std::setw;
 9
10   unsigned long factorial( unsigned long ); // function prototype
11
12   int main()
13   {
14      // calculate the factorials of 0 through 10
15      for ( int counter = 0; counter <= 10; counter++ )
16         cout << setw( 2 ) << counter << "! = " << factorial( counter )
17            << endl;
18
19      return 0;
20   } // end main
21
22   // iterative function factorial
23   unsigned long factorial( unsigned long number )
24   {
25      unsigned long result = 1;
26
27      // iterative factorial calculation           
28      for ( unsigned long i = number; i >= 1; i-- )
29         result *= i;                              
30
31      return result;
32   } // 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


Recursion has many negatives. It repeatedly invokes the mechanism, and consequently the overhead, of function calls. This can be expensive in both processor time and memory space. Each recursive call causes another copy of the function (actually only the function's variables) to be created; this can consume considerable memory. Iteration normally occurs within a function, so the overhead of repeated function calls and extra memory assignment is omitted. So why choose recursion?

Software Engineering Observation 6.16

Any problem that can be solved recursively can also be solved iteratively (nonrecursively). A recursive approach is normally chosen in preference to an iterative approach when the recursive approach more naturally mirrors the problem and results in a program that is easier to understand and debug. Another reason to choose a recursive solution is that an iterative solution is not apparent.


Performance Tip 6.9

Avoid using recursion in performance situations. Recursive calls take time and consume additional memory.


Common Programming Error 6.26

Accidentally having a nonrecursive function call itself, either directly or indirectly (through another function), is a logic error.