Factorial Program in C++

Written by

Juhi Kamdar

Factorial is the product of all the numbers starting from 1 till the given number.

For example: Factorial of 5 will be = 1*2*3*4*5 = 120

Note: Factorial of a negative number doesn’t exist. And, the factorial of 0 is 1.

Methods:

  1. Naïve approach
  2. Using Recursion

Method 1: Naïve approach

Logic:

Factorial of a non-negative integer x is the multiplication of all the integers smaller than or equal to x.

Algorithm:

  1. Take input of a number from the user.
  2. Initialize a variable to store the product of the numbers.
  3. Use a for loop to iterate from 1 to the given number.
  4. Multiply each number with the fact variable during each iteration.
  5. Print the final product as the output, which represents the factorial of the given number.

Code:

#include <iostream>
using namespace std;
int main()
{
    int n, fact = 1;
    cout << "Enter number";
    cin >> n;
    for (int i = 1; i <= n; i++)
        fact = fact * i;
    cout << "\n Factorial of given number is:" << fact;
    return 0;
}

Output:

Enter number: 6
Factorial of given number is:720

Method 2: Using function

Logic:

The same logic is used as above but here we are using function.

Algorithm:

  1. Take input of a number from the user.
  2. Initialize a variable to store the product of the numbers.
  3. Define a function that takes in 2 parameters: the current product and the current number.
  4. Use a for loop to iterate from 1 to the given number.
  5. Within the for loop, call the function and pass in the current product and current number as parameters.
  6. The function should multiply the current number with the current product.
  7. Store the returned value in the fact variable.
  8. Print the final value of the fact variable as the output, which represents the factorial of the given number.

Code:

#include <iostream>
using namespace std;
int factorial(int fact, int n)
{
    fact = fact * n;
    return fact;
}
int main()
{
    int n, fact = 1;
    cout << "Enter number";
    cin >> n;
    for (int i = 1; i <= n; i++)
        fact = factorial(fact, i);
    cout << "\n Factorial of given number is:" << fact;
    return 0;
}

Output:

Enter number: 7
Factorial of given number is: 5040
Factorial Program in C++