while Loops in C++

By: Manoj Kumar Emailed: 1604 times Printed: 2075 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

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.

while loops.

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.

Complex while loops.

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.

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(1)


1. View Comment

send c++ programs on every topic of c++

View Tutorial          By: mandeep at 2009-07-11 00:50:23

Your name (required):


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


Your sites URL (optional):


Your comments:



More Tutorials by Manoj Kumar
Importing Keystore example using keytool in Java
for loop example in Java
Result Sets, Cursors and Transactions in SQL
JSP Tags for SQL to connect to a database
Using the qsort() and bsearch() functions with values - example program in C
Using qsort() and bsearch() with strings - example program in C
scanf and sscanf sample program in C
Use of {0} is required and Accessing resource bundles programmatically in Struts
Character Arrays in C
Pointers to functions in C++
atoi(), itoa() in C++
Ticker sample program in J2ME
DateFormat sample program in Java
Random class sample program in Java - nextGaussian(), nextBoolean(), nextBytes(), nextInt(), nextLong(), nextFloat(), nextDouble()
What Is a Reference in 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++ )
C++ Recursion function explained using Fibonacci series
while Loops in C++
Using switch Statements in C++
ctime() sample program in C++
A Brief History of C++
Difference between Procedural, Structured, and Object-Oriented Programming
C++ and Object-Oriented Programming
Getting Started with C++
Using cout in C++
Using Comments in a C++ Program
Using functions in C++
How to use Enumerated constants in C++
Demonstration of Prefix and Postfix operators in C++
The if Statement in C++
Advanced if Statements in C++
Most Emailed Articles (in C++)
C++ and Object-Oriented Programming
Constructors and Destructors in C++
Pass by Reference in C++ functions
Vector variables in C++
The if Statement in C++
Nested Loops in C++
Operator Precedence in C++
strcat() and strncat() sample program in C++
Getting User Input Using cin in C++
Escape Sequences for Nonprintable Characters in C++
Classes with Other Classes as Member Data in C++
The Stack and the Free Store in C++
Dot (.) vs Arrow (->) to access data members in C++
Converting Pointer Parameters in C++ to Java
qsort() sample program in C++