Application: Summing the Even Integers from 2 to 20

The program of Fig. 5.5 uses a for statement to sum the even integers from 2 to 20. Each iteration of the loop (lines 11–12) adds control variable number’s value to variable total.

 1   // Fig. 5.5: fig05_05.cpp 2   // Summing integers with the for statement. 3   #include <iostream> 4   using namespace std; 5  6   int main() 7   { 8      unsigned int total = 0; // initialize total  9 10      // total even integers from 2 through 2011      for ( unsigned int number = 2; number <= 20; number += 2 )12         total += number;                                       13 14      cout << "Sum is " << total << endl; // display results15   } // end main

Sum is 110

Fig. ...

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

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