Home > Articles

This chapter is from the book

4.5 Application: Summing Even Integers

The application in Fig. 4.3 uses a for statement to sum the even integers from 2 to 20 and store the result in int variable total. Each iteration of the loop (lines 10–12) adds control variable number’s value to variable total.

 1   // fig04_03.cpp
 2   // Summing integers with the for statement.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main() {
 7      int total{0};
 8
 9      // total even integers from 2 through 20
10      for (int number{2}; number <= 20; number += 2) {
11         total += number;
12      }
13
14      cout << "Sum is " << total << "\n";
15   }
Sum is 110

Fig. 4.3 Summing integers with the for statement.

A for statement’s initialization and increment expressions can be comma-separated lists containing multiple initialization expressions or multiple increment expressions. Although this is discouraged, you could merge the for statement’s body (line 11) into the increment portion of the for header by using a comma operator as in

for (int number{2}; number <= 20; total += number, number += 2) { }

The comma between the expressions total += number and number += 2 is the comma operator, which guarantees that a list of expressions evaluates from left to right. The comma operator has the lowest precedence of all C++ operators. The value and type of a comma-separated list of expressions is the value and type of the rightmost expression, respectively. The comma operator is often used in for statements that require multiple initialization expressions or multiple increment expressions.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.