The factorial of a number is defined is the product of natural numbers from one to that particular number. Mathematically,
n! = 1 * 2 * 3 * …. * (n-1) * n
For example, the factorial of 5 is
5! = 1 * 2 * 3 * 4 *5= 120
This article will explain you how to find the factorial of a number through iteration as well as recursion.
C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> using namespace std; int fact (int i) { int result = 1; while (i > 0) { result = result * i; i = i-1; } return(result); } int main () { int n; cout << "Enter a natural number: "; cin >> n; while (n < 0) { cout << "Please re-enter: "; cin >> n; } cout << n << "! = " << fact(n) << endl; return(0); } /* OUTPUT: Enter a natural number: 5 5! = 120 */ |
C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> using namespace std; int main () { unsigned int n; unsigned long long factorial = 1; cout << "Enter a positive integer: "; cin >> n; for(int i = 1; i <=n; ++i) { factorial *= i; } cout << "Factorial of " << n << " = " << factorial; return(0); } /* OUTPUT: Enter a positive integer: 5 Factorial of 5 = 120 */ |
Output: