do...while Loops in C++
By: Abinaya in C++ Tutorials on 2007-09-09
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.
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.
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++
Comments