All loops may be labelled and the target of embedded break and continue statements.
while (test) statement; // "execute statement while test is true".
// The statement is never executed if test
// is false the first time.
|
| Common Programming Error |
while (test); // Putting a semicolon after the test
statement; // usually results in an infinite loop
// situatin is test is true, or
// unintended execution of the
// loop body statement if test is false.
|
do // execute a sequence of statements.
{
statement1;
statement2;
statement3;
} while (test); // continue executing the sequence while
// test is true.
// Even if the test is false the first
// time, the sequence is always executed at
// least once.
|
In the process of executing while and do loops, something should be happening that will eventually cause test to be false. Otherwise, you get into an "infinite loop" situation, where your program appears to be doing nothing, or writing the same message to the screen, again and again.
//for (initpart; testpart; incrpart)
for (int x=0; x < 10; x++ )
statement;
|
If the testpart evaluates to false, the loop terminates. The statement is not
executed. The incrpart is not evaluated.
while loop:
while (test) statement; | equivalent for loop:
for ( ;test; ) statement; |
do loop:
do{ statement; } while (test);
| near-equivalent1 for loop:
for (boolean dummy=true; dummy || test; dummy=false) statement;near-equivalent2 for loop: statement; for ( ;test; ) statement; |
A break statement may appear in the body of switch statements or loops.
In all cases, statements following the break are not executed, and the control structure terminates.
In the case of the for loop, the incrpart is NOT evaluated.
In the case of any loop, the test is NOT evaluated.
If the loop is in a sequence of statements, execution continues with the
statement following the loop.
| Break statements appear in two forms: | |
break; | break the innermost switch or loop |
break label; | break all switches or loops nested inside of the switch or loop labeled "label" |
Break statements rarely appear by themselves (in an absolute context). The statements are usually conditional.
if (isInfiniteLoop) break;
A continue statement may appear in the body of a loop.
Like a break statement, the continue statement causes statements following the break to be ignored, but for the current iteration only. The loop does not necessarily terminate.
In the case of the for loop, the increment part IS evaluated next.
Then the loop test expression is evaluated. If the expression is true, the
statements in the loop body are executed from the beginning. Otherwise, the
loop terminates normally.
| Continue statements appear in two forms: | |
continue; | only the current iteration of the loop is ended. the loop is not broken. |
continue label; | breaks all control structures nested within the loop with the named label. The loop with the named label is continued. |