C++ Continue Statement

The continue statement in C++ is used to skip the remaining code within the current iteration of a loop and proceed to the next iteration of the loop. It helps in skipping certain iterations based on a condition.

Syntax:

continue;

When continue is encountered, the loop immediately moves to the next iteration, bypassing any code that follows the continue statement within the current iteration.

Example: Using continue in a Loop

Here's a simple example demonstrating the use of the continue statement in a for loop:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 10; ++i) {
        if (i % 2 == 0) {
            continue; // Skip the rest of the loop for even numbers
        }
        cout << "i = " << i << endl;
    }
    return 0;
}

Output:

i = 1
i = 3
i = 5
i = 7
i = 9

In this example, the continue statement skips the remaining code for even values of i, so only odd values are printed.

C++ Continue Statement with Inner Loop

When used in nested loops, the continue statement affects only the innermost loop in which it is present. It will skip the remaining code in that loop's current iteration and move to the next iteration of that loop. The outer loop continues its execution as usual.

Example:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 3; ++i) {
        cout << "Outer loop iteration: " << i << endl;
        for (int j = 0; j < 3; ++j) {
            if (j == 1) {
                continue; // Skip the rest of the inner loop when j is 1
            }
            cout << " Inner loop iteration: " << j << endl;
        }
    }
    return 0;
}

Output:

Outer loop iteration: 0
Inner loop iteration: 0
Inner loop iteration: 2
Outer loop iteration: 1
Inner loop iteration: 0
Inner loop iteration: 2
Outer loop iteration: 2
Inner loop iteration: 0
Inner loop iteration: 2