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,
- Program to Calculate the Factorial Using While
- Program to Calculate the Factorial Using Recursion
- Program to Calculate the Factorial Using Do While
- Program to Calculate the Factorial Using For Loop
- Program to Calculate Factorial Using Static Storage Class
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