The iterative factorial method. : function recursion « Function « C++ Tutorial






#include <iostream>
using std::cout;
using std::endl;

#include <iomanip>
using std::setw;

unsigned long factorial( unsigned long );

int main()
{
   for ( int counter = 0; counter <= 20; counter++ )
      cout << setw( 2 ) << counter << "! = " << factorial( counter ) << endl;

   return 0;
}
unsigned long factorial( unsigned long number )
{
   unsigned long result = 1;

   for ( unsigned long i = number; i >= 1; i-- )
      result *= i;

   return result;
}
0! = 1
 1! = 1
 2! = 2
 3! = 6
 4! = 24
 5! = 120
 6! = 720
 7! = 5040
 8! = 40320
 9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 1932053504
14! = 1278945280
15! = 2004310016
16! = 2004189184
17! = 4006445056
18! = 3396534272
19! = 109641728
20! = 2192834560








7.11.function recursion
7.11.1.Demonstrate recursion
7.11.2.Print a string backwards using recursion
7.11.3.Recursive factorial function
7.11.4.The recursive fibonacci function.
7.11.5.The iterative factorial method.