- 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.4 Examples Using the for Statement
The following examples show techniques for varying the control variable in a for statement. In each case, we write only the appropriate for header. Note the change in the relational operator for the loops that decrement the control variable.
Vary the control variable from 1 to 100 in increments of 1.
for (int i{1}; i <= 100; ++i)
Vary the control variable from 100 down to 1 in decrements of 1.
for (int i{100}; i >= 1; --i)
Vary the control variable from 7 to 77 in increments of 7.
for (int i{7}; i <= 77; i += 7)
Vary the control variable from 20 down to 2 in decrements of 2.
for (int i{20}; i >= 2; i -= 2)
Vary the control variable over the values 2, 5, 8, 11, 14, 17, 20.
for (int i{2}; i <= 20; i += 3)
Vary the control variable over the values 99, 88, 77, 66, 55, 44, 33, 22, 11, 0.
for (int i{99}; i >= 0; i -= 11)
Do not use equality operators (!= or ==) in a loop-continuation condition if the loop’s control variable increments or decrements by more than 1. For example, in the for statement header
for (int counter{1}; counter != 10; counter += 2)
counter != 10 never becomes false (resulting in an infinite loop) because counter increments by 2 after each iteration, producing only the odd values (3, 5, 7, 9, 11, …).