Calculate Factorial of a Number in C++

Codeblocks Visual Studio Code

To calculate the factorial of a number in C++, you can use a loop to multiply all the numbers from 1 up to the specified number. Here's an example program:

#include <iostream>
using namespace std;

int main() {
    int num;
    unsigned long long factorial = 1;

    // Get the number for which you want to calculate the factorial
    cout << "Enter a non-negative integer: ";
    cin >> num;

    // Calculate the factorial
    for (int i = 1; i <= num; ++i) {
        factorial *= i;
    }

    cout << "Factorial of " << num << " = " << factorial << endl;

    return 0;
}

The program prompts the user to enter a non-negative integer.

It then uses a for loop to iterate through the numbers from 1 to num.

Inside the loop, it multiplies each number with the factorial variable.

Finally, it prints out the factorial of the input number.

Keep in mind that factorials can grow very large, so I've used an unsigned long long data type to handle larger values.

For example, if the user enters 5, the program will calculate the factorial of 5:

Factorial of 5 = 120

You can modify this program to calculate the factorial for different values by changing the user input.

Comments
Loading...
Sorry! No comment found:(

There is no comment to show for this.

Leave your comment
Tested Versions
  • GCC 6.3.0