Write a C++ Program to Find Factorial

Calculating the factorial of a given number is a common problem in mathematics and computer science.

In this tutorial, we will write a C++ program to find the factorial of a given number.

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers up to n. For example, 5! is equal to 5 × 4 × 3 × 2 × 1 = 120.

To calculate the factorial of a given number, we can use a loop to iterate from 1 to the given number and multiply each number in the loop with a variable that keeps track of the product.

Here’s the C++ code to find the factorial of a given number:

#include <iostream>
using namespace std;

int main() {
    int num, fact = 1;
    cout << "Enter a number: ";
    cin >> num;
    for (int i = 1; i <= num; i++) {
        fact *= i;
    }
    cout << "The factorial of " << num << " is " << fact << endl;
    return 0;
}

In this code, we first declare two integer variables num and fact. num is used to store the number whose factorial we want to find, and fact is used to store the product of all the numbers in the loop.

We then use the cout and cin statements to ask the user for the input number.

Next, we use a for loop to iterate from 1 to the input number. In each iteration of the loop, we multiply the current value of fact by the loop variable i and update the value of fact.

Finally, we use another cout statement to output the result of the factorial calculation.

That’s it! We have successfully written a C++ program to find the factorial of a given number.