C++ Program to Calculate Factorial of Entered Number using For, While, Do While

C++ Program to Calculate Factorial of Entered Number using For, While, Do While, Write a program to calculate factorial of entered number using for, while, do while,


Write a program to calculate factorial of entered number using  for, while, do while,

i.       
for loop,
Source Code:
#include<iostream.h>
#include<conio.h>
void main()
{
    int num,a,factorial=1;
    cout<<"Enter number to find its Factorial:";
    cin>>num;
      for(a=1; a<=num; a++)
      {
          factorial=factorial*a;
      }
      cout<<"The Factorial of"<<num<<"="<<factorial<<endl;
      getch();
}
Output:
Enter number to find its Factorial:5
The Factorial of5=120

ii.       do while loop and
Source Code:
#include<iostream.h>
#include<conio.h>
void main()
{
    int num, i, factorial=1;
    do
    {
        cout<<"Enter the number:"<<endl;
        cin>>num;
        for(i=1; i<=num; i++)
        factorial*=i;
        cout<<"Factorial of"<<num<<"is:"<<factorial;
    }
    while(num<=2 && num>=30);
    system("Pause");
    getch();
}
Output:
Enter the number:
5
Factorial of5is:120
Press any key to continue . . .
iii.     while loop.
Source Code:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int no,fact=1,i;
cout<<"Enter the no."<<endl;
cin>>no;
i=1;
while(i<=no)
{
fact=fact*i;
i++;
}
cout<<"The factorial is "<<fact;
getch();
}
                                Output:
Enter the no.
5

The factorial is 120

You May Also Like...