continue

Summary

Exits the current loop iteration and skips to the next loop iteration. If no loop iterations remain, the program will continue executing from the statement following the exited loop.

Syntax

continue [label];

Parameters

label
The label associated with a loop.

Description

continue can only be used inside a loop. It will end the current loop iteration and skip to the next loop iteration. If no loop iterations remain, the loop will exit, and the program will continue executing from the statement following the exited loop.

Before skipping to the next loop iteration:

  • In a while loop, the condition is checked first.
  • In a for loop, the update expression is executed and the condition is checked.

Basic Usage

In its simplest form, the continue statement will skip to the next loop iteration.

1
2
3
4
5
6
7
8
9
10
import System;
 
for (int i = 1; i <= 5; ++i) {
    // Skip third iteration
    if (i == 3) {
        continue;
    }
 
    Console.log(i);
}

Inside nested loops, the nearest loop enclosing the continue statement will be skipped. For instance:

1
2
3
4
5
6
7
8
9
10
11
for (int x = 1; x <= 5; ++x) {
    if (x == 2) {
        continue; // skips the second iteration of the loop iterating over 'x'
    }
     
    for (int y = 1; y <= 5; ++y) {
        if (y == 3) {
            continue; // skips the third iteration of the loop iterating over 'y'
        }
    }
}

Usage with Labels

In order to exit the outer loop from an inner loop, we would have to use labels. If we label the loops, we can refer to the outer loop explicitly from the continue statement:

1
2
3
4
5
6
7
outerLoop: for (int x = 1; x <= 5; ++x) {
    innerLoop: for (int y = 1; y <= 5; ++y) {
        if (x == 2) {
            continue outerLoop; // skips to the third iteration of the loop iterating over 'x'
        }
    }
}

Examples

Skipping all Even Integers
1
2
3
4
5
6
7
8
9
10
11
import System;
 
for (int i = 1; i <= 10; ++i) {
    // Modulus operator will divide by 2 and check if the remainder is zero (0)
    bool isEven = ( i % 2 == 0 );  
    if (isEven) {
        continue;
    }
     
    Console.log(i);
}

See Also

Share

HTML | BBCode | Direct Link