Difference between continue and break

In C#, both the continue and break statements are used to alter the flow of control in loops, but they serve different purposes:

continue statement: The continue statement is used to skip the remaining statements in the current iteration of a loop and move on to the next iteration. It allows you to bypass certain code within the loop based on a specific condition. After the continue statement is encountered, the loop immediately jumps to the next iteration, ignoring any code that follows it in the current iteration.
Here's an example to illustrate the use of the continue statement:


for (int i = 1; i <= 5; i++)
{
    if (i == 3)
        continue; // Skip the current iteration when i is 3

    Console.WriteLine(i);
}

In the above code, when i is equal to 3, the continue statement is executed. As a result, the Console.WriteLine(i) statement is skipped for that iteration. The loop continues with the next iteration, printing the values 1, 2, 4, and 5.

break statement: The break statement is used to exit or terminate a loop or a switch statement prematurely. It allows you to completely exit the loop or switch statement and resume program execution from the next statement after the loop or switch. When the break statement is encountered, the control flow jumps immediately out of the loop or switch, bypassing any remaining code within it.
Here's an example to demonstrate the use of the break statement:


while (true)
{
    string input = Console.ReadLine();

    if (input == "exit")
        break; // Exit the loop if the user enters "exit"

    Console.WriteLine("You entered: " + input);
}

In the above code, the while loop continues indefinitely until the user enters "exit" as the input. When the user enters "exit", the break statement is executed, causing the program to exit the loop and move on to the code after the loop.

To summarize, the continue statement skips the remaining code within the current iteration of a loop and moves to the next iteration, while the break statement completely exits the loop or switch statement, allowing program execution to continue from the statement immediately after the loop or switch.