// Fig. 3.14: fig03_14.cpp // Recursive factorial function #include #include #include long factorial( short ); int main( int argc, char* argv[] ) { int tableSize = 1; if (argc > 1) tableSize = atoi(argv[1]); for ( short i = 0; i <= tableSize; i++ ) cout << setw( 2 ) << i << "! = " << factorial( i ) << endl; return 0; } /* definition of factorial: for a positive integer n, n! is 1*2*...*n, and 0! is 1. Thus 4! = 1*2*3*4 = 24. */ ///// Recursive definition of function factorial long factorial( short number ) { if ( number <= 1 ) // base case return 1; else // recursive case return number * factorial( number - 1 ); } ///// Another recursive definition of function factorial long fact2( short n ) { return (n <= 1) ? 1 : n*fact2( n - 1 ); } ///// An iterative definition of factorial long fact3( short n ) { long result; result = 1; for ( short k = n; k > 1; k-- ) { result *= k; } return result; }