To find out the factorial of a number is an easy task. For example factorial of 4 (4!) is 4 x 3 x 2 x 1 = 24. Now, the question is how do we do that in a computer program? Here, I will show you two ways. We have to note that it was assumed that 0! is 1 so keeping in mind the value, here is the code:
1. Using Simple Function:
#include<iostream> using namespace std; int fact(int n); int main() { int number; cout << "Enter a number: "; cin >> number; cout << "Factorial is: " << fact(number) << endl; return 0; } int fact(int n) //Factorial using a simple while loop in a function { int result=n; if (n == 1 || n == 0) return 1; else { while (n>1) { result *= (n-1); n--; } return result; } }
2. Factorial using a Recursive Function: A recursive function is a function that call itself.
#include<iostream> using namespace std; int factorial(int n); int main() { int number; cout << "Enter a number: "; cin >> number; cout << "Factorial is: " << factorial(number) << endl; return 0; } int factorial(int n) // using recursive function to find out the factorial of any number. { if (n == 1 || n == 0) return 1; else return (n * factorial(n - 1)); }
I think there are many other way to achieve this problem but the above two are the most common ones.