for Loops

When programming while loops, you'll often find yourself setting up a starting condition, testing to see if the condition is true, and incrementing or otherwise changing a variable each time through the loop. Listing 6.7 demonstrates this.

Listing 6.7. while Loop Reexamined
 0:  // Listing 6.7
 1:  // Looping with while
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      int counter = 0;
 7:
 8:      while(counter < 5)
 9:      {
10:          counter++;
11:          std::cout << "Looping!  ";
12:      }
13:
14:      std::cout << "\nCounter: " << counter << ".\n";
15:      return 0;
16:  }
Looping!  Looping!  Looping!  Looping!  Looping!
counter: 5.
					

The condition is set on line 6: counter ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.