while Loops in C++
By: Manoj Kumar in C++ Tutorials on 2007-09-09
A while loop causes your program to repeat a sequence of statements as long as the starting condition remains true. The following program shows advantages of a while loop instead of using goto statements.
1: // 2: // Looping with while 3: 4: #include <iostream.h> 5: 6: int main() 7: { 8: int counter = 0; // initialize the condition 9: 10: while(counter < 5) // test condition still true 11: { 12: counter++; // body of the loop 13: cout << "counter: " << counter << "\n"; 14: } 15: 16: cout << "Complete. Counter: " << counter << ".\n"; 17: return 0; 18: } Output: counter: 1 counter: 2 counter: 3 counter: 4 counter: 5 Complete. Counter: 5.
Analysis: This simple program demonstrates the fundamentals of the while loop. A condition is tested, and if it is true, the body of the while loop is executed. In this case, the condition tested on line 10 is whether counter is less than 5. If the condition is true, the body of the loop is executed; on line 12 the counter is incremented, and on line 13 the value is printed. When the conditional statement on line 10 fails (when counter is no longer less than 5), the entire body of the while loop (lines 11-14) is skipped. Program execution falls through to line 15.
The while Statement
The syntax for the while statement is as follows:
while ( condition ) statement;
condition is any C++ expression, and statement is any valid C++ statement or
block of statements. When condition evaluates to TRUE (1),
statement is executed, and then condition is tested again. This continues until
condition tests FALSE, at which time the while loop terminates
and execution continues on the first line below statement.
Example
// count to 10 int x = 0; while (x < 10) cout << "X: " << x++;
More Complicated while Statements
The condition tested by a while loop can be as complex as any legal C++ expression. This can include expressions produced using the logical && (AND), || (OR), and ! (NOT) operators. Listing 7.3 is a somewhat more complicated while statement.
1: // 2: // Complex while statements 3: 4: #include <iostream.h> 5: 6: int main() 7: { 8: unsigned short small; 9: unsigned long large; 10: const unsigned short MAXSMALL=65535; 11: 12: cout << "Enter a small number: "; 13: cin >> small; 14: cout << "Enter a large number: "; 15: cin >> large; 16: 17: cout << "small: " << small << "..."; 18: 19: // for each iteration, test three conditions 20: while (small < large && large > 0 && small < MAXSMALL) 21: 22: { 23: if (small % 5000 == 0) // write a dot every 5k lines 24: cout << "."; 25: 26: small++; 27: 28: large-=2; 29: } 30: 31: cout << "\nSmall: " << small << " Large: " << large << endl; 32: return 0; 33: } Output: Enter a small number: 2 Enter a large number: 100000 small: 2......... Small: 33335 Large: 33334
Analysis: This program is a game.
Enter two numbers, one small and one large. The smaller number will count up by
ones, and the larger number will count down by twos. The goal of the game is to
guess when they'll meet.
On lines 12-15, the numbers are entered. Line 20 sets up a while loop,
which will continue only as long as three conditions are met:
small is not bigger than large.
large isn't negative.
small doesn't overrun the size of a small integer (MAXSMALL).
On line 23, the value in small is calculated modulo 5,000. This does
not change the value in small; however, it only returns the value 0
when small is an exact multiple of 5,000. Each time it is, a dot (.)
is printed to the screen to show progress. On line 26, small is
incremented, and on line 28, large is decremented by 2.
When any of the three conditions in the while loop fails, the loop ends
and execution of the program continues after the while loop's closing
brace on line 29.
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