The do while loop

 

The do while loop works same as the while loop and the loop is iterated as long as condition remains true. The do while loop checks the condition at the bottom of the loop while for and while loop checks the condition at the beginning of the loop and as a result the body of the loop is executed at least once. The general form of the do while loop is: -

 

do{

   statement;

} while(condition);

 

The body of the loop is executed until the condition becomes false. Here is a program which illustrates the working of the do while loop.

 

 

The result of the program is: -

 

 

In the program the condition is checked at the end of the loop by the statement

 

            while(str==’y’);

The body of the loop is iterated once without checking the given condition. The statements

                        cout << “Enter the number you want to add” << endl;

                        cin >>i;

allow the user to enter the number to be added. Then the statements

                       

                        cout << “Do you want to enter the number y/n” << endl;

                        cin >> str;

ask the user whether he or she wants to add another number. If the user enters ‘y’ then the condition is true and the loop is executed once more. If the user enters any character other than ‘y’ then the condition is false and loop is terminated.

 

After an introduction of loops, let us move on to discuss arrays.

 

 

 

 

 

 

           

 

                       

           

 

Go to the previous lesson or proceed to the next lesson
Table of contents