Factorial

A factorial is a product of an integer and all the integers below it. In other words, factorial (!) Is the product of all integers from 1 to n.

For example:

If N = 5, then 5! is 5 x 4 x 3 x 2 x 1 = 120

Logic

First of all, we declare one temporary variable fact with value 1, now we are going to use this variable to store factorial.

After taking input from the user, we need to start one loop from 1 to N, and inside the loop we multiply current number “i” with variable fact and then store the result again in fact variable until the loop terminates. Once the loop is over we have to print the fact variable containing factorial of a given number (N).

Program

#include <iostream>

using namespace std;

int main() {

    int i, num;
    int fact = 1;

    // Take numbers from user
    cout << "Enter any number : ";
    cin >> num;

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

    cout << endl << "Factorial of " << num << " : " << fact;

    return 0;
}

Output

Enter any number : 5
Factorial of 5 : 120