next up previous
Next: Statements to exit from Up: Unit 06 Previous: Example of elimination of

The continue statement (optional)

The continue statement can be used only within loops, and its effect is to directly jump to the next loop iteration, skipping for the current iteration those statements that follow in the loop body.

Example: Print out the odd numbers between 0 and 100.

for (int i = 0; i <= 100; i++) {
  if (i % 2 == 0)
    continue;
  System.out.println(i);
}

Note that, when a continue statement is used in a for loop, the update-statement of the for loop is not skipped and is executed anyway.

Note: A possible use of continue is within a loop for reading from input, in which we want to execute some operations on the read data item only if a certain condition is satisfied. However, we have to make sure that at each iteration of the loop, the next data item is read in any case; otherwise the loop would not terminate.

Example: Wrong use of the continue statement.

read the first data item;
while (condition) {
  if (condition-on-the-current-data)
    continue;         // ERROR! the reading of the next data item is skipped
  process the data;
  read the next data item;
}


next up previous
Next: Statements to exit from Up: Unit 06 Previous: Example of elimination of