We now consider a sample app that demonstrates a simple use of for
. The app in Fig. 6.5 uses a for
statement to sum the even integers from 2 to 20 and store the result in an int
variable called total
. Each iteration of the loop (lines 12–15) adds control variable number
’s value to variable total
.
The initialization and increment expressions can be comma-separated lists that enable you to use multiple initialization expressions or multiple increment expressions. For example, although this is discouraged, you could merge the for
’s body statement (line 14) into the increment portion of the for
header by using a comma as follows:
total += number, number += 2