C# `continue` Statement: Controlling Loop Iteration

Master loop control in C# with the `continue` statement. This tutorial explains how `continue` skips the remaining code in the current loop iteration and proceeds to the next, enhancing the flexibility and efficiency of your C# loops. Learn how to use `continue` effectively in both single and nested loops.



Understanding C#'s `continue` Statement

The C# `continue` statement is a control flow statement used within loops (like `for` and `while` loops). It alters the loop's execution by skipping the rest of the current iteration and proceeding to the next iteration.

How `continue` Works

When the `continue` statement is encountered within a loop, the program immediately jumps to the next iteration of that loop. Any code after the `continue` statement within the current iteration is skipped. If the `continue` is within a nested loop, it only affects the inner loop.

Example 1: `continue` in a Single Loop

This example demonstrates the `continue` statement in a single `for` loop. The loop iterates from 1 to 10, but when `i` is 5, the `continue` statement skips the `WriteLine` for that iteration.


for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        continue; // Skip the rest of this iteration
    }
    Console.WriteLine(i);
}

Example 2: `continue` in Nested Loops

This example shows `continue` within nested loops. The `continue` statement only affects the inner loop (`j`).


for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            continue; // Skip the rest of this inner loop iteration
        }
        Console.WriteLine($"{i} {j}");
    }
}