Summary: In this programming example, we will learn different ways to calculate the factorial of a number in C++.

Factorial of any positive integer n denoted by n! is the product of all positive integers less than or equal to n.

i.e. n! = n×(n-1)×(n-2)×(n-3)×⋯×3×2×1.

There are different ways to find factorial of a number in C++. Let’s see the example of each of them.

Method 1: Factorial using Loop

#include <iostream>
using namespace std;

int main() {
    int n;
    unsigned long long factorial= 1;
    
    cout << "Enter a number \n";
    cin >> n;
    
    for(int i=n; i>=1; i--){
        factorial = factorial*i;
    }
    
    cout << "Factorial of " << n << " is " << factorial;
    return 0;
}

Output

Enter a number
5
Factorial of 5 is 120


In this method, we loop from n to 1 in decreasing order and simultaneously multiply each number with the factorial variable.

The final value of factorial is the product of all numbers from n to 1 i.e. factorial of n.

The factorial of a number is always positive and could exceed the range of int in C++, that’s why we used the unsigned long long type to store the factorial value.

Method 2: Factorial using Function

#include <iostream>
using namespace std;

unsigned long long findFactorial(int n){
    unsigned long long factorial= 1;
    
    for(int i=n; i>=1; i--){
        factorial = factorial*i;
    }
    return factorial;
}

int main() {
    int n;
    
    cout << "Enter a number \n";
    cin >> n;
    
    cout << "Factorial of " << n << " is " << findFactorial(n);
    return 0;
}

Output

Enter a number
6
Factorial of 6 is 720


This method is similar to the above discussed method but incorporated using a function.

The function using loop algorithm calculates and returns the factorial of the number n.

Method 3: Factorial using Recursion

#include <iostream>
using namespace std;

//Recursive Function
unsigned long long factorial(int n){
    if(n==0 || n==1)
        return 1;
    return n*factorial(n-1);
}

int main() {
    int n;
    
    cout << "Enter a number \n";
    cin >> n;
    
    cout << "Factorial of " << n << " is " << factorial(n);
    return 0;
}

Output

Enter a number
7
Factorial of 7 is 5040


In this program, factorial(int n) is a recursive method with a base condition of n==1 || n==0.

If the base condition is not satisfied then we multiply the value n with the next recursive call i.e. factorial(n-1).

The factorial of n is returned back to the main function at the end of the recursion.

In this tutorial, we learned to calculate factorial of a number in C++.

Leave a Reply

5 + 6 =