- 4.1 Introduction
- 4.2 Essentials of Counter-Controlled Iteration
- 4.3 for Iteration Statement
- 4.4 Examples Using the for Statement
- 4.5 Application: Summing Even Integers
- 4.6 Application: Compound-Interest Calculations
- 4.7 do... while Iteration Statement
- 4.8 switch Multiple-Selection Statement
- 4.9 C++17 Selection Statements with Initializers
- 4.10 break and continue Statements
- 4.11 Logical Operators
- 4.12 Confusing the Equality (==) and Assignment (=) Operators
- 4.13 Objects-Natural Case Study: Using the miniz-cpp Library to Write and Read ZIP files
- 4.14 C++20 Text Formatting with Field Widths and Precisions
- 4.15 Wrap-Up
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.