C++ Program to find Factorial of a number


February 9, 2023, Learn eTutorial
1221

What is meant by the factorial of a number?

How we find the Factorial of number in C++?

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++.

How to write a C++ program to find the factorial?

Prompt the user to enter an input. Read the number to the integer variable n. declare a long double variable fact = 1.

  • Print an error if the entered number n < 0. ( negative integers).
  • Print the value of fact as 1 if the n is 0
  • Calculate the factorial for other numbers using a for loop. start a for loop from 1 to n and calculate fact  *= i, inside the loop

Note: The factorial of zero is defined as one ie., 0 ! = 1


 

Algorithm

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.

 

C++ Source Code

                                          #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;
}
                                      

OUTPUT

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