Difference between break and continue Statements in C#

When we need to exit the current loop, we use the break statement. The continue statement, on the other hand, is used to continue the current loop for the next iteration, skipping the execution of the block of code available after the statement for the current iteration. For example:

Console.WriteLine("Using the 'break' statement'");
for (int i = 0; i < 10; i++)
{
    if (i == 4)
        break;
    Console.WriteLine(i);
}

Console.WriteLine("\nUsing the 'continue' statement");
for (int i = 0; i < 10; i++)
{
    if (i == 4)
        continue;
    Console.WriteLine(i);
}

The snapshot given below shows the sample output produced by this C# example.

c sharp break continue

As you can see from the above C# example demonstrating the break and continue statements, in the first for loop, when the condition i == 4 evaluates to true, the break statement is executed, and the program flow goes out of the loop. Whereas there was a different scenario with the "continue" statement. That is, in the second for loop, when the same condition evaluates to be true, the continue statement is executed, and the statement after the continue statement is skipped during its execution for that iteration. The program flow then transfers for the next iteration of the loop.

C# Online Test


« Previous Tutorial Next Tutorial »