while Loops

Demonstrated in Listing 6.1, a while loop causes your program to repeat a sequence of statements as long as the starting condition remains true.

Listing 6.1. while Loops
 0:  // Listing 6.1
 1:  // Looping with while
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      int counter = 0;            // initialize the condition
 7:
 8:      while(counter < 5)          // test condition still true
 9:      {
10:          counter++;              // body of the loop
11:          std::cout << "counter: " << counter << "\n";
12:      }
13:
14:      std::cout << "Complete. counter: " << counter << ".\n";
15:      return 0;
16:  }
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
Complete. counter: 5

This simple program ...

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.