Programming

C++ – Calculate Factorial using For, While, Do While

Write a program to calculate the factorial of an 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 a number to find its Factorial:5
The Factorial of5=120

ii.       do-while loop

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

Tuts

About Author

Tutsmaster.org provides tutorials related to tech and programmings. We are also setting up a community for the users and students.