Signup/Sign In

C++ Factorial of a given Number Program

Hello Everyone!

In this tutorial, we will learn how to find the Factorial of a given number using the C++ programming language.

Code:

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to find the Factorial of a given number ===== \n\n";

    //variable declaration
    int i,n;

    //as we are dealing with the product, it should be initialized with 1.
    int factorial=1;

    //taking input from the command line (user)
    cout << "Enter the number to find the factorial for: ";
    cin >> n;

    //finding the factorial by multiplying all the numbers from 1 to n
    for (i = 1; i <= n; i++)
    {
        factorial *= i; // same as factorial = factorial * i 
    }

    cout << "\n\nThe Factorial of " << n << " is: " << factorial;

    cout << "\n\n\n";

    return 0;
}

Output:

C++ factorial program

Now let's see what we have done in the above program.

Program Explained:

Let's break down the parts of the code for better understanding.

What's a Factorial in Mathematics?

In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n:

Note:

  1. Factorial is only defined for non-negative numbers. (>=0)

  2. The value of 0 factorial is 1. (0! = 1)

 //as we are dealing with the product, it should be initialized with 1.
    int factorial=1;

As Factorial is only defined for a non-negative integers, it always results into a positive integer value. Also, initializing it to 1 as the multiplication operation is involved in the logic given below.

1. Logic for finding the factorial using C++:

// finding the factorial by multiplying all the numbers from 1 to n
for (i = 1; i <= n; i++)
{
    factorial *= i; // same as factorial = factorial * i
}

As per the above definition, we need to take the product of all the numbers starting from 1 to the number itself. Loop is the best way to achieve this.

factorial *= i;

This is same as factorial = factorial * i, but an easier way to code.

This works for all the mathematical operations such as +, -, /, %.

Wil recommend you to try this out on yourself to develop better understanding.

Keep Learning : )



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.