Using a Recursive factorial Function to Calculate Factorials

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).

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.