4.2.Do while loop
Do while loop different of while and for loop, its process statement first before checking condition and will process again and again if condition true and will stop when condition failed, but at least its will process once time without true condition.
Syntax:
do { statement ; increment / decrement; }while(condition);
Example 1:
#include<iostream.h> #include<conio.h> void main() { int i=100; do { cout<<"I: "<<i<<endl; i--; }while(i>0); getch(); }
Example 2:
#include<iostream.h> #include<conio.h> void main() { int i=1,n; float sum=0; cout<<"Enter n: "; cin>>n; cout<<"Sum= "; cout.setf(ios::showpoint|ios::fixed); cout.precision(2); do{ cout<<"1/"<<i<<"+"; sum+=1.0/i++; }while(i<=n); cout<<"\b= "<<sum; getch(); }
Example 3:
#include<iostream.h> #include<conio.h> void main() { int n; float fac=1; cout<<"Enter n: "; cin>>n; cout<<"Factorial = "; cout.setf(ios::showpoint|ios::fixed); cout.precision(2); do{ cout<<n<<" * "; fac*=n--; }while(n>=1); cout<<"\b\b= "<<fac; getch(); }