The factorial of a number 'n' can be calculated by multiplying the numbers from '1' to 'n'. The Factorial of '0' is '1' and we cannot able to find the factorial for negative numbers. It is denoted by the symbol '!'.
n! = 1 * 2 * 3 * 4 *……..* n.
5! = 1*2 *3*4*5 = 120.
Here you will learn to calculate the factorial of a number using for loop in C++.
Prompt the user to enter an input. Read the number to the integer variable n. declare a long double variable fact = 1.
for loop.
start a for loop from 1 to n and calculate fact *= i, inside the loopNote: The factorial of zero is defined as one ie., 0 ! = 1
Step 1: Call the header file iostream.
Step 2: Use the namespace std
.
Step 3: Open the integer type main function; int main().
Step 4: Declare integer variables; n, fact
Step 5: Print a message to enter a positive integer.
Step 6: Read the user input into the variable n.
Step 7: Print an error message if n < 0. Else go to step 8
Step 8: for i = 1 to n; fact *= i; print fact
Step 9: print fact = 1 for 0!
Step 10: Exit.
#include <iostream>
using namespace std;
int main() {
int n;
long double fact = 1.0;
cout << "Enter a positive integer: ";
cin >> n;
if (n < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= n; ++i) {
fact *= i;
}
cout << "Factorial of " << n << " = " << fact;
}
return 0;
}
Run 1 Enter a positive integer: 9 Factorial of 9 = 362880 Run 2 Enter a positive integer: -8 Error! Factorial of a negative number doesn't exist. Run 3 Enter a positive integer: 0 Factorial of 0 = 1