ptg7068951
96 HOUR 8: Repeating an Action with Loops
for (int dex = 0; dex < 1000; dex++) {
if (dex % 12 == 0) {
System.out.println(“#: “+ dex);
}
}
This loop displays every number from 0 to 999 evenly divisible by 12.
Every forloop has a variable that determines when the loop should begin
and end. This variable is called the counter (or index). The counter in the
preceding loop is the variable dex.
The exampleillustrates the three parts of a forstatement:
. The initialization section: In the first part, the dexvariable is given an
initial value of 0.
. The conditional section: In the second part, there is a conditional test
like one you might use in an ifstatement: dex < 1000.
. The change section: The third part is a statement that changes the
value of the dexvariable, in this example by using the increment
operator.
In the initialization section, you set up the counter variable. You can create
the variable in the forstatement, as the preceding example does with the
integer variable dex. You also can create the variable elsewhere in the pro-
gram. In either case, you should give the variable a starting value in this sec-
tion of the forstatement. The variable has this value when the loop starts.
The conditional section contains a test that must remain truefor the loop
to continue looping. When the test is false, the loop ends. In this example,
the loop ends when the dexvariable is equal to or greater than 1,000.
The last section of the forstatement contains a statement that changes the
value of the counter variable. This statement is handled each time the loop
goes around. The counter variable has to change in some way or the loop
never ends. In the example, dexis incremented by one in the change sec-
tion. If dexwas not changed, it would stay at its original value of 0 and the
conditional dex < 1000always would be true.
The forstatement’s block is executed during each trip through the loop.
The preceding example had the following statements in the block:
if (dex % 12 == 0) {
System.out.println(“#: “+ dex);
}