C.15. for Repetition Statement

Java also provides the for repetition statement, which specifies the counter-controlled-repetition details in a single line of code. Figure C.13 reimplements the application of Fig. C.12 using for.


 1   // Fig. C.13: ForCounter.java
 2   // Counter-controlled repetition with the for repetition statement.
 3
 4   public class ForCounter
 5   {
 6      public static void main( String[] args )
 7      {
 8         // for statement header includes initialization, 
 9         // loop-continuation condition and increment     
10         for ( int counter = 1; counter <= 10; ++counter )
11            System.out.printf( "%d ", counter );          
12
13         System.out.println(); // output a newline
14      } // end main
15   } // end class ForCounter

1 2 3 4 5 6 7 8 9 10
s


Fig. C.13 | Counter-controlled repetition with the for repetition statement.

When the for statement (lines 10–11) begins executing, the control variable counter is declared and initialized to 1. Next, the program checks the loop-continuation condition, counter <= 10, which is between the two required semicolons. Because the initial value of counter is 1, the condition initially is true. Therefore, the body statement (line 11) displays control variable counter’s value, namely 1. After executing the loop’s body, the program increments counter in the expression ++counter, which appears to the right of the second semicolon. Then the loop-continuation test is performed again to determine whether the program should continue with the next iteration of the loop. At this point, the control variable’s value is 2, so the condition is still true (the final value is not exceeded)—thus, the program performs the body statement again (i.e., the next iteration of the loop). This process continues until the numbers 1 through 10 have been displayed and the counter’s value becomes 11, causing the loop-continuation test to fail and repetition to terminate (after 10 repetitions of the loop body). Then the program performs the first statement after the for—in this case, line 13.

Figure C.13 uses (in line 10) the loop-continuation condition counter <= 10. If you incorrectly specified counter < 10 as the condition, the loop would iterate only nine times. This is a common logic error called an off-by-one error.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset