Iterative Factorial Implementation

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.

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.