Java Reference
In-Depth Information
then update is performed. If initialization and update are omitted, then the
for statement behaves exactly like a while statement. The advantage of a for
statement is clarity in that for variables that count (or iterate), the for statement
makes it much easier to see what the range of the counter is. The following frag-
ment prints the first 100 positive integers:
for( int i = 1; i <= 100; i++ )
System.out.println( i );
This fragment illustrates the common technique of declaring a counter in the ini-
tialization portion of the loop. This counter's scope extends only inside the loop.
Both initialization and update may use a comma to allow multiple expres-
sions. The following fragment illustrates this idiom:
for( i = 0, sum = 0; i <= n; i++, sum += n )
System.out.println( i + "\t" + sum );
Loops nest in the same way as if statements. For instance, we can find all
pairs of small numbers whose sum equals their product (such as 2 and 2,
whose sum and product are both 4):
for( int i = 1; i <= 10; i++ )
for( int j = 1; j <= 10; j++ )
if( i + j == i * j )
System.out.println( i + ", " + j );
As we will see, however, when we nest loops we can easily create programs
whose running times grow quickly.
Java 5 adds an “enhanced” for loop. We discuss this addition in Section
2.4 and Chapter 6.
1.5.6 the do statement
The while statement repeatedly performs a test. If the test is true , it then
executes an embedded statement. However, if the initial test is false , the
embedded statement is never executed. In some cases, however, we would
like to guarantee that the embedded statement is executed at least once. This
is done using the do statement. The do statement is identical to the while
statement, except that the test is performed after the embedded statement.
The syntax is
The do statement is
a looping construct
that guarantees the
loop is executed at
least once.
do
statement
while( expression );
next statement
 
Search WWH ::




Custom Search