C Continue

The continue statement in C is used to skip the remaining part of the current loop iteration and move directly to the next iteration. It helps to control the flow within loops by bypassing certain parts of the loop body based on a specific condition.

Syntax:

// Inside a loop
continue;

Example 1: Skipping Even Numbers in a Loop

#include <stdio.h>

int main() {
    int i;

    for (i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue; // Skip the rest of the loop body for even numbers
        }
        printf("%d\\n", i); // Print only odd numbers
    }

    return 0;
}

Output:

1
3
5
7
9

Example 2: Skipping Specific Values

#include <stdio.h>

int main() {
    int i = 1;

    while (i <= 10) {
        if (i == 5) {
            i++; // Increment before continuing to avoid an infinite loop
            continue; // Skip the rest of the loop body for number 5
        }
        printf("%d\\n", i); // Print all numbers except 5
        i++;
    }

    return 0;
}

Output:

1
2
3
4
6
7
8
9
10

Important Considerations

Scope of continue: The continue statement only affects the loop in which it is placed. It does not terminate the loop but rather skips to the next iteration.

Impact on Loop Execution: After the continue statement is executed, control is passed to the loop's conditional check, which determines if the loop should proceed with the next iteration.

Use in Nested Loops: When used in nested loops, the continue statement only affects the innermost loop where it is placed