C++ Program to find Factorial of a number

Here you will learn to calculate the factorial of a number using for loop in C++ in this example.

How can we calculate the factorial of a number?

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

The factorial of a number is the product of all integers from 1 to that number. Factorial is not defined for negative numbers, and the factorial of zero is one. An exclamation mark indicates the factorial of a number '!'.
n! =  1 * 2 * 3 * 4 *……..* n.
5! = 1*2 *3*4*5 = 120.

C++ program to find the factorial of a given number.

The user is asked to enter a positive integer. Read the number to the integer variable n. declare a long double variable fact = 1.0;Long double refers to a floating-point data type that is often more precise than double precision.

  • Print a message error if the entered number n < 0. ( negative integers).
  • Print the value of fact if n = 0 .( 0! = 1 )
  • Calculate the factorial for other numbers using a for loop

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


for ( i = 1; i<= n; i++ )
{ fact *= i; }
 

Print fact and finish the program.

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 number 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