Saturday, 22 September 2018

Calculating a factorial of a number in C++

Factorial of a number

Factorial of a number is obtained multiplying all the positive integer equal to or less than the number whose factorial is to be calculated. It is the product of all positive integer from 1 to the number.
It is represented by the number along with an exclamation symbol. 

E.g.  Factorial of 5 is represented as 5! and is calculated as:
                                                                       5!=5*4*3*2*1=120

For any number n, its factorial is obtained as:
                                                                         n!= n * (n-1)!

The factorial of Zero is one (i.e. 0!=1). The factorial of negative and decimal number doesn't exist.



Write a program in C++ to input a number from the user and calculate its factorial.


First, we need to input a number from the user and assign it to a variable. Then we execute a for loop
from 1 to the input number. We multiply all the number that is obtained during the execution of the for loop(i.e. from 1 to input number). Finally, we get the factorial of the number.


Program


#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,i;
long int fact=1;
cout<<"Enter the number whose factorial you want to calculate=";
cin>>a;
for(i=1;i<=a;i++)
{
fact=fact*i;
}
cout<<"\n The factorial of "<<a<<" = "<<fact;
getch();
}


Output


Calculation of factorial of a number
FACTORIAL CALCULATION OF THE GIVEN NUMBER




   



Explanation


In the program, we entered the value 7. So the for loop was executed from 1 to 7(i.e. i=1 to 7). Each time the for loop was executed the value of i was multiplied with fact and stored in fact. In this way, the product of all values of i was calculated which is our required value. Finally, the value i.e factorial of 7 was displayed on the screen.





No comments:

Post a Comment