Doing Things at Least Once

In many cases, you want to do something at least once and perhaps many times. This is best handled by the do/while loop.

The form of this loop is

do
{
   statements
}
while (condition);

Let's have a look at its use in the main() function of the division calculator (see Listing 9.1).

Listing 9.1. A do/while Loop in main()
 1: int main(int argc, char* argv[]) 2: { 3: SAMSErrorHandling::Initialize(); 4: *5: do // At least once... *6: { 7: try 8: { 9: float Dividend = GetDividend(); 10: float Divisor = GetDivisor(); 11: 12: cout << Divide(Dividend,Divisor) << endl; 13: } 14: catch (...) 15: { 16: SAMSErrorHandling::HandleNotANumberError(); 17: } ; *18: } *19: while (SAMSPrompt::UserWantsToContinue ("More division? ")); 20: ...

Get SAMS Teach Yourself C++ in 10 Minutes SECOND EDITION 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.