C++ Program to Find Factorial

To understand this example, you should have the knowledge of the following C++ programming topics:


The factorial of a number is the product of all the integers from 1 up to that number. The factorial can only be defined for positive integers.

The factorial of a negative number doesn't exist. And the factorial of 0 is 1.

For example,

The factorial of a positive number n, say 5, is denoted by 5! and is given by:

5! = 1 * 2 * 3 * 4 * 5 = 120

So, the Mathematical logic for factorial is:

n! = 1 * 2 * 3 * ... * n
n! = 1 if n = 0 or n = 1

In this program, the user is asked to enter a positive integer. Then the factorial of that number is computed and displayed on the screen.


Example: Find the Factorial of a Given Number

#include <iostream>
using namespace std;

int main() {
    int n;
    long factorial = 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) {
            factorial *= i;
        }
        cout << "Factorial of " << n << " = " << factorial;    
    }

    return 0;
}

Output

Enter a positive integer: 4
Factorial of 4 = 24

In this program, we take a positive integer from the user and compute the factorial using for loop. We print an error message if the user enters a negative number.

We declare the type of factorial variable as long since the factorial of a number may be very large.

When the user enters a positive integer (say 4), for loop is executed and computes the factorial. The value of i is initially 1.

The program runs until the statement i <= n becomes false. This prints Factorial of 4 = 24 on the screen. Here’s how the program executes when n = 4.

i <= 4 fact *= i
1 <= 4 fact = 1 * 1 = 1
2 <= 4 fact = 1 * 2 = 2
3 <= 4 fact = 2 * 3 = 6
4 <= 4 fact = 6 * 4 = 24
5 <= 4 Loop terminates.

Note: This program can calculate the factorial only up to the number 20. Beyond that, the program can no longer calculate the factorial as the results exceed the capacity of the factorial variable.

Did you find this article helpful?