Java Reference
In-Depth Information
Initialize loop variable
Loop test condition
Increment loop variable
for ( loopCounter = 1; loopCounter <= 3; loopCounter++)
{
// execute this code
}
Code looped through
Figure 3-10
The fi rst part of the for statement's logic is the initialization part of the for statement. To keep track of
how many times you have looped through the code, you need a variable to keep count. It's in the initial-
ization part that you initialize variables. In the example you have declared loopCounter and set it to
the value of 1. This part is only executed once during the execution of the loops, unlike the other parts.
You don't need to declare the variable if it was declared earlier in the code.
var loopCounter;
for (loopCounter = 1; loopCounter <= 3; loopCounter++)
Following the semicolon, you have the test condition part of the for statement. The code inside the for
statement will keep executing for as long as this test condition evaluates to true. After the code is looped
through each time, this condition is tested. In Figure 3-10, you execute for as long as loopCounter is less
than or equal to 3. The number of times a loop is performed is often called the number of iterations .
Finally, you have the increment part of the for loop, where variables in our loop's test condition have
their values incremented. Here you can see that loopCounter is incremented by one by means of the
++ operator you saw in Chapter 2. Again, this part of the for statement is repeated with every loop of
the code. Although we call it the increment part, it can actually be used to decrease or decrement the
value — for example, if you wanted to count down from the top element in an array to the fi rst.
After the for statement comes the block of code that will be executed repeatedly, as long as the test con-
dition is true. This block of code is contained within curly braces. If the condition is never true, even
at the fi rst test of the loop condition, then the code inside the for loop will be skipped over and never
executed.
Putting all this together, how does the for loop work?
1.
Execute initialization part of the for statement.
2.
Check the test condition. If true , continue; if not, exit the for statement.
Search WWH ::




Custom Search