The following examples show methods of varying the control variable in a for
statement. In each case, we write the appropriate for
statement header. Note the change in the relational operator for loops that decrement the control variable.
a) Vary the control variable from 1
to 100
in increments of 1
.
for ( unsigned int i = 1; i <= 100; ++i )
b) Vary the control variable from 100
down to 0
in decrements of 1
. Notice that we used type int
for the control variable in this for
header. The condition does not become false until control variable i
contains -1
, so the control variable must be able to store both positive and negative numbers.
for ( int i = 100; i >= 0; --i )
c) Vary the control variable from 7
to 77
in steps of 7
.
for ( unsigned int i = 7; i <= 77; i += 7 )
d) Vary the control variable from 20
down to 2
in steps of -2
.
for ( unsigned int i = 20; i >= 2; i -= 2 )
e) Vary the control variable over the following sequence of values: 2
, 5
, 8
, 11
, 14
, 17
.
for ( unsigned int i = 2; i <= 17; i += 3 )
f) Vary the control variable over the following sequence of values: 99
, 88
, 77
, 66
, 55
.
for ( unsigned int i = 99; i >= 55; i -= 11 )
Common Programming Error 5.2
Not using the proper relational operator in the loop-continuation condition of a loop that counts downward (such as incorrectly using i <= 1 instead of i >= 1 in a loop counting down to 1) is a logic error that yields incorrect results when the program runs.
Common Programming Error 5.3
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 consider the for statement header for ( unsigned int counter = 1; counter != 10; counter += 2 ). The loop-continuation test counter != 10 never becomes false (resulting in an infinite loop).