C# Continue Statement

In C#, the continue statement is used to skip the rest of the code within a loop iteration and move on to the next iteration. It is commonly used in loops such as for, while, and do-while to control the flow of execution.

Here’s the general syntax of the continue statement in C#:

continue;

When the continue statement is encountered within a loop, the remaining statements within that loop iteration are skipped, and the program jumps to the next iteration of the loop.

Here’s an example to illustrate the usage of the continue statement:

for (int i = 1; i <= 5; i++)
{
    if (i == 3)
    {
        continue;
    }
    Console.WriteLine(i);
}

In this example, we have a for loop that iterates from 1 to 5. When i is equal to 3, the continue statement is executed, causing the loop to skip the remaining statements for that iteration. As a result, the number 3 is not printed to the console. The output of this code will be:

1
2
4
5

Note that the continue statement can only be used within loop constructs. If you try to use it outside of a loop, it will result in a compilation error.

C# Continue Statement with Inner Loop:

The continue statement can also be used within an inner loop to skip the rest of the code within the inner loop iteration and continue with the next iteration of the inner loop. This allows you to control the flow of execution within nested loops.

Here’s an example that demonstrates the usage of the continue statement with an inner loop:

for (int i = 1; i <= 3; i++)
{
    for (int j = 1; j <= 3; j++)
    {
        if (j == 2)
        {
            continue;
        }
        Console.WriteLine($"i = {i}, j = {j}");
    }
}

In this example, we have two nested for loops. The outer loop iterates from 1 to 3, and the inner loop also iterates from 1 to 3. When the value of j is equal to 2 in the inner loop, the continue statement is executed, causing the inner loop to skip the remaining statements for that iteration and move on to the next iteration. As a result, the numbers where j is 2 are not printed to the console.

The output of this code will be:

i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3

As you can see, the numbers where j is 2 (2, 2, and 2) are skipped due to the continue statement.

The continue statement can be useful in scenarios where you want to skip certain iterations within nested loops based on specific conditions, allowing you to fine-tune the flow of execution in your program.