Problem: Write a C++ program to calculate factorial of a number.

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

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

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

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