The while Loop

The while statement is another way of affecting the order of program execution. This conditional statement executes the statement under its control as long as a certain condition is true. Such potentially repeated execution is called a loop; a loop controlled by a while statement is called, logically enough, a while loop. Figure 3.23 is a program that uses a while loop to challenge the user to guess a secret number from 0 to 9, and keeps asking for guesses until the correct answer is entered.

Figure 3.23. Using a while statement (code\basic04.cpp)
 #include <iostream> using namespace std; int main() { short Secret; short Guess; Secret = 3; cout << "Try to guess my number. Hint: It's from 0 to 9" << endl; cin >> Guess; while (Guess ...

Get C++: A Dialog Programming with the C++ Standard Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.