while
while
while, do-while, and for control
looping. A statement repeats until the controlling expression evaluates to
false. The form of a while loop is
while(expression)
statement
The expression is evaluated once at the beginning of
the loop and again before each further iteration of the
statement.
This example stays in the body of the while
loop until you type the secret number or press control-C.
//:
C03:Guess.cpp
//
Guess a number (demonstrates "while")
#include
<iostream>
using
namespace
std;
int
main() {
int
secret = 15;
int
guess = 0;
// "!=" is the "not-equal"
conditional:
while(guess
!= secret) { // Compound
statement
cout << "guess the
number: ";
cin >> guess;
}
cout << "You guessed
it!" << endl;
}
///:~
The while's conditional expression is
not restricted to a simple test as in the example above; it can be as
complicated as you like as long as it produces a true or false
result. You will even see code where the loop has no body, just a bare
semicolon:
while(/*
Do a lot here */)
;
In these cases, the programmer has written the
conditional expression not only to perform the test but also to do the
work.
|