How to find the factorial of a number in C++

In this shot, we will discuss how to use a for loop to find the factorial of a number in C++.

The factorial of a number is the product of all the integers less than that number, until 1. The symbol that represents factorial is an exclamation point, i.e., !.

Let’s take a look at the following image to understand this better.

Factorial of a number

In the image above, we calculate the factorial of number 5. We multiply all the integers less than 5. The factorial of 5 is 120.

We will use the for loop to calculate the factorial of a number.

Let’s see the code snippet below to understand it better.

#include <iostream>
using namespace std;
int main() {
int number, factorial=1 ;
cin >> number;
for (int i = number; i >= 1 ; i--)
{
factorial = factorial * i;
}
cout << "The factorial of the given number is: " << factorial << endl;
return 0;
}

Enter the input below

Explanation

Enter a value in the above code to generate an output.

  • In line 5, we initialize the number and factorial variables.

  • In line 6, we take the input as number.

  • In line 7, we initialize a for loop, where we give conditions to run the loop until i>=1 and use a decrement operator to take the values in decreasing order.

  • In line 9, whenever the loop iterates, the value is stored in factorial until the loop gets terminated.

  • In line 11, we print the factorial value of a number stored in the variable factorial.

In this way, we can use loops to calculate the factorial of a number in C++.

Free Resources