I know this has been asked 100 times before and I searched the posts but I didn't find the code so I'll ask. How do you write a code that calculates the faculty for n, i.e. n! ?
I know this has been asked 100 times before and I searched the posts but I didn't find the code so I'll ask. How do you write a code that calculates the faculty for n, i.e. n! ?
Code:#include <iostream> using std::cout; int factorial(int input); int main() { cout << factorial(3) << "\n"; return 0; } int factorial(int input) { for (int output=1; input > 0; input--) output = output * input; return output; }
Last edited by MadCow257; 03-26-2005 at 12:20 PM.
Recursive function
Code:#include <iostream> #include <stdlib.h> using namespace std; int factorial(int fac) { if(fac == 1) { return fac; } else { return fac * factorial(fac - 1); } } int main() { int fac; cout << "INPUT: "; cin >> fac; cout << "FACTORIAL OF " << fac << " IS " << factorial(fac) << endl; system("PAUSE"); return 0; }
Last edited by mrafcho001; 03-26-2005 at 12:38 PM.