/* testfunc11.cpp CIS 150 6/9/2005 David Klick Factorial functions. */ #include #include using std::cout; using std::setw; int factn(int); // non-recursive factorial function int factr(int); // recursive factorial function int main(void) { int i; cout << "Non-recursive factorial calcs:\n"; for (i=0; i<=10; i++) { cout << "The factorial of " << setw(2) << i << " is " << setw(7) << factn(i) << '\n'; } cout << "\nRecursive factorial calcs:\n"; for (i=0; i<=10; i++) { cout << "The factorial of " << setw(2) << i << " is " << setw(7) << factr(i) << '\n'; } return 0; } /* Non-recursive factorial function */ int factn(int n) { int prod = 1; while (n > 0) prod *= n--; return prod; } /* Recursive factorial function */ int factr(int n) { if (n < 2) return 1; return n * factr(n-1); } /* Sample output: Non-recursive factorial calcs: The factorial of 0 is 1 The factorial of 1 is 1 The factorial of 2 is 2 The factorial of 3 is 6 The factorial of 4 is 24 The factorial of 5 is 120 The factorial of 6 is 720 The factorial of 7 is 5040 The factorial of 8 is 40320 The factorial of 9 is 362880 The factorial of 10 is 3628800 Recursive factorial calcs: The factorial of 0 is 1 The factorial of 1 is 1 The factorial of 2 is 2 The factorial of 3 is 6 The factorial of 4 is 24 The factorial of 5 is 120 The factorial of 6 is 720 The factorial of 7 is 5040 The factorial of 8 is 40320 The factorial of 9 is 362880 The factorial of 10 is 3628800 */