C++ | Factorial of a number

Hello peeps! Lord Hypersonic greets you. Today I am presenting you a C++ program to find the factorial of the number given by the user. Just user have to enter the number and it will print the factorial of that number.
Before discussing the algorithm to find factorial, first, let us understand what the heck is this factorial.

What is factorial?

Factorial of a number n is represented as n!. It is equal to the product of numbers smaller than equal to n. For example, if we want to find the factorial of 5 then we have to do it like this:-

5!  = 5 * 4 * 3 * 2 * 1  = 120

Similarly, if we want to find the factorial of 4, it will look like this:-

4! = 4 * 3 * 2 * 1 = 24

Algorithm

Now let us see the algorithm to find the factorial of a number. Its algorithm is very simple:-

1. First, declare two integer variables n and factorial and initialize factorial with 1.

2. Start a loop from i = n to i >= 1.
     2.2. At each iteration, make factorial = factorial * i

3. After the loop is finished, print the value of factorial.

THAT'S IT!

THIS IS THE ALGORITHM TO FIND A FACTORIAL OF A NUMBER.  

Now let us see an example to understand the algorithm more clearly. Let us assume, the user enters 5, so the value of n is equal to 5.
Starting a loop from i = 5 to i >= 1.
At each iteration, value of factorial = factorial * 1.
So, at first iteration, factorial = 1 * 5 = 5
at second iteration, factorial = 5 * 4 = 20
at third iteration, factorial = 20 * 3 = 60
at fourth iteration, factorial = 60 * 2 = 120
at fifth iteration, factorial = 120 * 1 = 120
As i = 1, loop will terminate and factorail is eqaul to 120.
Now just print the value of factorial.
That's it. 
This is how you can make a program to find the factorial of a number in any programming language.

SOURCE CODE:-

/*
Program: factorial
Description: Find factorial of the given number.
Author: Lord Hypersonic
Email: lordhypersonic.522@gmail.com
Website: www.lordhypersonic.blogspot.com
*/
#include <iostream>

using namespace std;

int main()
{
    int n,factorial=1;
    cout<<"Find factorial of : "; cin>>n;
    for (int i = n; i >= 1; i--)
    {
        factorial = factorial * i;
    }
    cout<<endl<<n<<"! = "<<factorial<<endl;
    return 0;
}


No comments

Powered by Blogger.