do...while Loops

It is possible that the body of a while loop will never execute. The while statement checks its condition before executing any of its statements, and if the condition evaluates false, the entire body of the while loop is skipped. Listing 6.5 illustrates this.

Listing 6.5. Skipping the Body of the while Loop
 0:  // Listing 6.5
 1:   // Demonstrates skipping the body of
 2:   // the while loop when the condition is false.
 3:  #include <iostream>
 4:
 5:  int main()
 6:  {
 7:      int counter;
 8:      std::cout << "How many hellos?: ";
 9:      std::cin >> counter;
10:      while (counter > 0)
11:      {
12:          std::cout << "Hello!\n";
13:          counter--;
14:      }
15:      std::cout << "counter is OutPut: " << counter;
16:      return 0;
17:  }
 How many hellos?: 2 Hello! Hello! counter ...

Get Sams Teach Yourself C++ in 24 Hours, Third 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.