do...while Loops in C++

By: Abinaya Emailed: 1784 times Printed: 2614 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

It is possible that the body of a while loop will never execute. The while statement checks its condition before executing any of its statements, and if the condition evaluates false, the entire body of the while loop is skipped. The following C++ program illustrates this.

Skipping the body of the while Loop.

1:     // 
2:      // Demonstrates skipping the body of
3:      // the while loop when the condition is false.
4:
5:      #include <iostream.h>
6:
7:      int main()
8:      {
9:         int counter;
10:        cout << "How many hellos?: ";
11:        cin >> counter;
12:        while (counter > 0)
13:        {
14:           cout << "Hello!\n";
15:           counter--;
16:        }
17:        cout << "Counter is OutPut: " << counter;
18:         return 0;
19: }
Output: How many hellos?: 2
Hello!
Hello!
Counter is OutPut: 0

How many hellos?: 0
Counter is OutPut: 0

Analysis: The user is prompted for a starting value on line 10. This starting value is stored in the integer variable counter. The value of counter is tested on line 12, and decremented in the body of the while loop. The first time through counter was set to 2, and so the body of the while loop ran twice. The second time through, however, the user typed in 0. The value of counter was tested on line 12 and the condition was false; counter was not greater than 0. The entire body of the while loop was skipped, and Hello was never printed.
What if you want to ensure that Hello is always printed at least once? The while loop can't accomplish this, because the if condition is tested before any printing is done. You can force the issue with an if statement just before entering the while:

if (counter < 1)  // force a minimum value
counter = 1;

but that is what programmers call a "kludge," an ugly and inelegant solution.

do...while

The do...while loop executes the body of the loop before its condition is tested and ensures that the body always executes at least one time. The program below rewrites the program shown above, this time using a do...while loop.

Demonstrates do...while loop.

1:      // 
2:      // Demonstrates do while
3:
4:      #include <iostream.h>
5:
6:      int main()
7:      {
8:         int counter;
9:         cout << "How many hellos? ";
10:        cin >> counter;
11:        do
12:        {
13:           cout << "Hello\n";
14:           counter--;
15:        }  while (counter >0 );
16:        cout << "Counter is: " << counter << endl;
17:         return 0;
18: }

Output: How many hellos? 2
Hello
Hello
Counter is: 0

Analysis: The user is prompted for a starting value on line 9, which is stored in the integer variable counter. In the do...while loop, the body of the loop is entered before the condition is tested, and therefore the body of the loop is guaranteed to run at least once. On line 13 the message is printed, on line 14 the counter is decremented, and on line 15 the condition is tested. If the condition evaluates TRUE, execution jumps to the top of the loop on line 13; otherwise, it falls through to line 16.
The continue and break statements work in the do...while loop exactly as they do in the while loop. The only difference between a while loop and a do...while loop is when the condition is tested.

The do...while Statement

The syntax for the do...while statement is as follows:

do
statement
while (condition);

statement is executed, and then condition is evaluated. If condition is TRUE, the loop is repeated; otherwise, the loop ends. The statements and conditions are otherwise identical to the while loop. Example 1

// count to 10
int x = 0;
do
cout << "X: " << x++;
while (x < 10)

Example 2

// print lowercase alphabet.
char ch = `a';
do
{
cout << ch << ` `;
ch++;
} while ( ch <= `z' );

 


DO use do...while when you want to ensure the loop is executed at least once. DO use while loops when you want to skip the loop if the condition is false. DO test all loops to make sure they do what you expect.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(16)


1. View Comment

HELP ME HOW TO ANALZE THE PROGRAM??????????

View Tutorial          By: MICHELLE FLORES at 2009-01-21 23:24:52
2. View Comment

.. nice one ..
.. aNg gLing nka2'amazing ..


View Tutorial          By: ma'kHuLet at 2010-01-19 19:25:19
3. View Comment

thanks for all thanks for your help good bye

View Tutorial          By: ARAS at 2010-05-14 06:50:47
4. View Comment

pls help me .....its hard to understand for me the programming .........thank you!!! for the example.....

View Tutorial          By: heidi at 2010-06-27 02:31:29
5. View Comment

Thank you......... It's very helpful.

View Tutorial          By: Ramesh Kumar Mahto at 2010-09-01 12:12:30
6. View Comment

help me pls example ng c++ program code using do while??

View Tutorial          By: diana bernardo at 2010-10-15 23:34:19
7. View Comment

Hy plz help me for also draw to flowchart..........thank you It's very helpful.

View Tutorial          By: khadija at 2010-11-13 11:38:31
8. View Comment

HI guys i am also studying c++ And now almost master of c++ and visual c++ as well join me at facebook at Inayat619@hotmail.com and at gmail at the id of inayat619@gmail.com
its hard in begning but cool after some experience


View Tutorial          By: Inayat Ullah at 2011-02-08 09:29:44
9. View Comment

There something at Example #2! because when i try it there are 13errors appear?
what a problem?


View Tutorial          By: Paul at 2011-08-01 14:38:14
10. View Comment

can you help me do this? - write a program that will display the ff. pattern, given the value of n. ex. if n=4, output
*
**
***
****


View Tutorial          By: rence at 2011-08-16 13:33:14
11. View Comment

0

View Tutorial          By: zareen at 2011-08-20 08:27:28
12. View Comment

i really hate do while loop statement, can u pls help me in my assignment...my instructor told us to make a program using do while loop..and here it is:
First Sales Amount:
Bonus(10%)
Next Sales Amount:
Bonus(15%)
Next Sales Amount:
Bonus(20%)
Next Sales Amount:
Bonus(25%)
Total Sales Amount:
Total Bonus:

pls help me....


View Tutorial          By: mARjO at 2011-09-01 03:50:18
13. View Comment

Can you give some examples of do while & please help me in my assignment like marjo???tnx

View Tutorial          By: mhilan at 2011-09-01 04:54:13
14. View Comment

3 - To build features that realize the control elements with a negative value if the vector V which
contains N element indices are in positions to:
a. For cycle (5 points)
b. Cycle Do - While (5 points)
c. While cycle (5 points)
d. Recursive functions (10 points)
does anyone know this


View Tutorial          By: kosovari at 2012-01-30 13:52:54
15. View Comment

/
//BSIT
//
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
double rPay,oPay,tax,nPay,pRate,hrswrkd,otPay,gPay,quit=0,total=0,total1=0,total2=0;
int noOfemployees=0;
char eCode,lCode,choice;
do{
cout<<"Enter the payrate: ";
cin>>pRate;
cout<<"Enter the number of hours worked: ";
cin>>hrswrkd;
cout<<"Enter the employee code (A or B): ";
cin>>eCode;
cout<<"Enter the location code (N or P): ";
cin>>lCode;
cout<<endl;
noOfemployees++;
total+=gPay+gPay;
total1+=nPay+nPay;
total2+=tax+tax;
if(hrswrkd<=40)
{rPay=pRate*hrswrkd;
otPay=0; }
else if (hrswrkd>40)
{rPay=pRate*40;
otPay=(1.5*pRate)*(hrswrkd-40);}
cout<<"Regular Pay: "<<rPay<<endl;
cout<<"Overtime Pay: "<<otPay<<endl;
gPay=rPay+otPay;
cout<<"Gross Pay: "<<gPay<<endl;
if(eCode=='A'&&lCode=='N')
tax=gPay*0.07;
else if(eCode=='A'&&lCode!='N')
tax=gPay*0.045;
else if(eCode!='A')
tax=0;
cout<<"Tax: "<<tax<<endl;
cout<<"---------------------"<<endl;
nPay=gPay-tax;
cout<<"Net pay: "<<nPay<<endl;
cout<<endl;
cout<<"Do you want to process another employee? (y/n): "<<endl;
cin>>choice;
if(choice!='y')
quit=0;
}while(choice!='n');
quit=1;

cout<<"Total number of employees processed:"<<noOfemployees<<endl;
cout<<"Total gross pay:"<<total<<endl;
cout<<"Total Tax:"<<total2<<endl;
cout<<"Total net pay:"<<total1<<endl;
getch();
}

i need to know the formula of TOTAL please help me


View Tutorial          By: Joshua Torres at 2012-10-05 16:59:17
16. View Comment

Please, I need help, how can i write a program "while"
for this out put:


*****************
Telephone Digits
*****************
Program to convert uppercase letters to their corresponding telephone digits.
To stop the program enter #.
Enter a letter: S

The letter you entered is S
The corresponding telephone digit is :7

Enter another uppercase letter to find its corresponding telephone digit. To stop the program enter #.
Enter a letter: @

Invalid input

Enter another uppercase letter to find its corresponding telephone digit. To stop the program enter #.
Enter a letter: A

The letter you entered is A
The corresponding telephone digit is :2


Enter another uppercase letter to find its corresponding telephone digit. To stop the program enter #.
Enter a letter: #

Thank you .


View Tutorial          By: LULU at 2012-11-23 01:34:07

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Abinaya
How to compile a Java program - javac
The clone() Method in Java
Data Types in Java
JSP Example to connect to MS SQL database and retrieve records
faces-config.xml to DirectTraffic in the JSF Application
Enabling Expression Language Evaluation in JSP
Using malloc() Function in C
ActionErrors and ActionError in Struts
Open, Creat, Close, Unlink system calls sample program in C
Structures and Functions in C
Introduction to JSP expression language
Multi-dimensional Arrays in C (Explained using date conversion program)
A C program similar to grep command in UNIX
Type Conversions in C (String to Integer, isdigit() etc)
Basics of C

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Using cout.width() in C++
Calculating total based on the given quantity and price in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Dot (.) vs Arrow (->) to access data members in C++
Constructors and Destructors in C++
Calculate average using Two-Dimensional Array in C++
C++ Recursion function explained using Fibonacci series
assert() example program in C++
cin.ignore() in C++
Using peek() and putback() with cin in C++
Programming errors a compiler will detect in C++
Multiple statements in for loops in C++
Using Comments in a C++ Program
Using cout in C++
Sorting an array of Strings in C++
Most Emailed Articles (in C++)
Using cout.width() in C++
Two-Dimensional Array Manipulation in C++
Sorting an array of Strings in C++
Using cout in C++
Printing values in DEBUG mode in C++
File in C++ - Writing text to a file in C++
while loop in C++
Interface Versus Implementation in C++
C++ Sample Program for Allocating, using, and deleting pointers.
How to handle Exceptions in C++
Multiple inheritance example in C++
Vector variables in C++
Using the Built-in Arithmetic Types in C++
Compute the square root of the sum of the squares of an array in C++
Getting Started with C++