Friday 20 October 2017

Do While Loop

DO... WHILE LOOP      

Do... while is another type of looping.It is quite different from the for loop but similar to the while loop with one important difference. In do... while loop initialization at the top of the loop, update condition inside the loop and test condition at bottom of the loop.The body of do..while loop is executed once, Before checking the test expression. Hence the do...while loop is executed at least once.

syntax:-
do
{
   // codes
}
while (testExpression);
program to add numbers until the user enters zero:-
#include <iostream>
using namespace std;
int main()
{    

    double number, sum = 0;
    
    do
    {
        cout<<"Enter a number: ";
        cin>>number;
        sum += number;
    }
    while(number != 0.0);

    cout<<"Sum: "<<sum<<endl;

    return 0;
}
Output:-
Enter a number: 5
Enter a number: -5
Enter a number: 21
Enter a number: 0
Sum: 21
Now take a look how do...while loop works?

The code inside the body will be executed once.
Then the test condition is evaluated.If the condition is true then the loop body will be executed again until the test condition becomes false.
when the test condition becomes false, the do...while loop will be terminated.

INFINITE DO... WHILE LOOP:-

#include<iostream>
using namespace std;
int main(){
 
 do{ 
 
  cout<<"hello world"<<endl;
  
  
 }while(1);
 
 return 0
}
Just provide 1 instead of the test condition, the loop will run infinite time.
NOTE:- press CTRL+C to terminate the loop.

NESTED DO...WHILE LOOP:-

#include<iostream>
using namespace std;
int main(){
 int i=0;
 do{
  
  int j=0;
  do{
   
   cout<<j;
   
   j++;
   
  }while(j<=5);
  i++;
  
  cout<<"\n";
  
 }while(i<=5);
 
 return 0;
}
Output:-
012345
012345
012345
012345
012345
012345
In nested do...while another do...while is present inside the body of the loop.It is similar to nested for and while loop.

Let take an example how do...while loop is different from other loops.

#include<iostream>
using namespace std;

int main(){
 
 int i=6;
 do{ 
 
 cout<<i<<endl;
 
 i++; 
  
 }while(i<=5);
 
 return 0;
}
 will this program work? yes,  it will work and print 6 on the screen because in do...while the condition is checked at the end of the program. 
we use do...while loop in game programming because when the game ends, you need to show the scoreboard to the player. we use do...while loop so at least once to render the scoreboard.

HAPPY CODING...




                                            

0 comments:

Post a Comment