Counter-Controlled Repetition
Click
while
/ for
to
see the concepts.
Counter-controlled repetition requires
// Fig. 5.1: WhileCounter.java // Counter-controlled repetition with the while repetition statement. public class WhileCounter { public static void main( String[] args ) { int counter = 1; // declare and initialize control variable while ( counter <= 10 ) // loop-continuation condition { System.out.printf( "%d ", counter ); ++counter; // increment control variable by 1 } // end while System.out.println(); // output a newline } // end main } // end class WhileCounter
for repetition statement
// Fig. 5.2: ForCounter.java // Counter-controlled repetition with the for repetition statement. public class ForCounter { public static void main( String[] args ) { // for statement header includes initialization, // loop-continuation condition and increment for ( int counter = 1; counter <= 10; counter++ ) System.out.printf( "%d ", counter ); System.out.println(); // output a newline } // end main } // end class ForCounter
A
common logic error with counter-controlled repetition is an
off-by-one error.
For example, if the above
condition is changed to
counter < 10, the loop
would iterate only nine times.
The general format of the for statement is
In most cases, the for statement can be represented with an equivalent while statement as follows:
initialization;
while ( loopContinuationCondition )
{
statement
increment;
}
Typically, for statements are used for counter-controlled repetition and while statements for sentinel-controlled repetition.
If the initialization expression in the for header declares the control variable, the control variable can be used only in that for statement.
A
variable’s
scope
defines where it can be used in a program.
A local variable can be used only in the method that declares it and only from
the point of declaration through the end of the method.
The increment expression in a for acts as if it were a standalone statement at the end of the for’s body, so
counter = counter + 1
counter += 1
++counter
counter++are equivalent increment expressions in a for statement.
for (int j = x; j <= 4 * x * y; j += y / x)
is equivalent to the statement
for (int j = 2; j <= 80; j += 5)