do-while
do
statement
while(expression);
The do-while is different from the
while because the statement always executes at least once, even if the
expression evaluates to false the first time. In a regular while, if the
conditional is false the first time the statement never
executes.
If a do-while is used in
Guess.cpp, the variable guess does not need an initial dummy
value, since it is initialized by the cin statement before it is
tested:
//: C03:Guess2.cpp
// The guess program using do-while
#include <iostream>
using namespace std;
int main() {
int secret = 15;
int guess; // No initialization needed here
do {
cout << "guess the number: ";
cin >> guess; // Initialization happens
} while(guess != secret);
cout << "You got it!" << endl;
} ///:~
For some reason, most programmers tend to
avoid do-while and just work with
while.