/* testfunc11.cpp CIS 150 2008-06-10 David Klick Factorial functions. */ #include #include using std::cin; using std::cout; using std::setw; int factn(int); // non-recursive factorial function int factr(int); // recursive factorial function void cont(); int main(int argc, char* argv[]) { 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'; } cont(); return 0; } /* int fact(int n); Arguments: int n: an arbitrary integer (s/b >= 0) Returns: The factorial of the argument n if n is >= 0, otherwise 1. Non-recursive factorial function */ int factn(int n) { int prod = 1; while (n > 0) prod *= n--; return prod; } /* int factr(int n); Arguments: int n: an arbitrary integer (s/b >= 0) Returns: The factorial of the argument n if n is >= 0, otherwise 1. Recursive factorial function */ int factr(int n) { if (n < 2) return 1; return n * factr(n-1); } /* void cont(); Arguments: none Returns: nothing Clears input buffer and pauses waiting for user to press Enter. */ void cont() { if (cin.rdbuf()->sungetc() != -1 && cin.get() != '\n') cin.ignore(80,'\n'); cout << "Press enter to continue..."; cin.get(); } /* 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 */