... factorial(counter)
13            << endl;
14      }
15   }
16
17   // iterative function factorial
18   unsigned long factorial(unsigned int number) {
19      unsigned long result{1};
20
21      // iterative factorial calculation
22      for (unsigned int i{number}; i >= 1; --i) {
23         result *= i;                            
24      }                                          
25
26      return result;
27   }

 
 0! = 1
 1! = 1
 2! = 2
 3! = 6
 4! = 24
 5! = 120
 6! = 720
 7! = 5040
 8! = 40320
 9! = 362880
10! = 3628800

Negatives of Recursion

Recursion has 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 variables to be created; this can consume considerable memory. Iteration normally occurs within a function, ...

Get C++ How to Program, 10/e now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.