Java Reference
In-Depth Information
for(inital statement; condition; end￿of￿block statement){
true
}
false
FIGURE 3.3: The for statement.
number reaches ten. Note that in the above code we started counting at 0. We could have
started counting at 1 and kept counting until we reached 10. However, computer scientists
often like to start counting at 0. For example, if a computer scientist counts tree apples, he
or she will most likely count: apple 0, apple 1, apple 2.
Counting is such a common operation when programming that Java supports a special
kind of loop just for counting that is called the for loop. The structure of the for loop is
shown in Figure 3.3. The for loop has three parts that are separated by semicolons. The first
part is executed at the beginning of the loop and it is executed only once. The second part
(a.k.a., the condition) is checked before the block of the loop is executed. If the condition is
true, then the block is executed. Otherwise, control jumps to the line immediately after the
for loop block. The third part of the for loop is executed after the block is executed and
before the condition is checked again. For example, our last code snippet can be elegantly
rewritten using a for statement as follows.
for ( int numTries = 0; numTries < = 9; numTries = numTries+1) {
...
}
The for block will be executed for numTries = 0 to 9. At the end of the tenth execution,
the statement numTries = numTries + 1 will be executed and numTries will become equal
to 10. Then the condition numTries <= 9 will become false and the program will jump to
the line immediately after the for loop.
The variable numTries is only valid inside the for loop.Itwewanttoexaminethevalue
of the variable numTries after the for loop, then we need to define it before the for loop
as shown next. In most cases, the counter is only used to keep track of how many times the
for loop block is executed and the first syntax is used.
int numTries ;
for (numTries = 0; numTries < =9; numTries=numTries+1) {
...
System. out . println (numTries) ;
The above program will print the number 10 if the for loop does not contain a break
statement. The variable numTries is referred to as the counter variable .
Java allows us to modify the value of the counter variable inside the for loop.
However, this is cheating . After running one lap, you can move the counter to ten and
say that you have run ten laps. In general, modifying the counter variable inside the
for block is considered poor programming practice.
 
Search WWH ::




Custom Search