Home C++ Factorial of a Number in C++

Factorial of a Number in C++

In this example we show you how to display the factorial of a number in C++

The factorial of a non negative number is the product of all the integers from 1 to that number.

For example, the factorial of 6 is 1*2*3*4*5*6 = 720 .

Example

#include <iostream>
using namespace std;

int main()
{
    cout << "Factorial of a number\n";

    //variable declaration
    int i,myNumber;
    int factorial=1;

    //take input from the user
    cout << "Enter the number to find the factorial for: ";
    cin >> myNumber;

    //find the factorial by multiplying all the numbers from 1 to n
    for (i = 1; i <= myNumber; i++)
    {
        factorial *= i;
    }

    cout << "\n\nThe Factorial of " << myNumber << " is: " << factorial;

    cout << "\n";

    return 0;
}

When you run this you will see something like this

Factorial of a number
Enter the number to find the factorial for: 6


The Factorial of 6 is: 720

You may also like