C++ PROGRAMS
Factorial of any natural number is the product of that number and all the natural numbers less than that. It is indicated with the help of the sign: ! .
For example:
4!= 4 X 3 X 2 X 1 = 24
8!= 8 X 7 X 6 X 5 X 4 X 3 X 2 X 1 = 40320
Note: 0! = 1
In the following program the user enters any natural number and the output is the factorial of that number.
In this I will use for-loop.
Code:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
long a,i,fact=1;
cout<<"Factorial"<<"\n";
cout<<"Enter any natural number: ";
cin>>a;
for(i=1;i<=a;i++)
{
fact=fact*i;
}
cout<<"Ans. "<<fact;
getch();
}
Output:
First Run:
Second Run:
Note: if you enter a number more than 10, then sometimes the output may be a junk value(random value). This is because the factorials of those numbers are very large.
For any queries or suggestions please comment !
No comments:
Post a Comment