Break Statement
The break statement is a control flow statement in C# used to terminate the execution of the enclosing loop or switch statement. It immediately exits the loop or switch block and proceeds to the code following the loop or switch.
Example:
int number = 1;
while (number <= 10) {
if (number == 5) {
break; // Terminate the loop when number equals 5
}
Console.WriteLine(number);
number++;
}
Continue Statement
The continue statement is a control flow statement in C# used to skip the remaining code in the current iteration of a loop and proceed to the next iteration. It immediately skips to the loop's beginning, where the condition is evaluated again for the next iteration.
Example:
for (int number = 1; number <= 10; number++) {
if (number % 2 == 0) {
continue; // Skip even numbers
}
Console.WriteLine(number);
}
Key Differences between Break and Continue Statements
Conclusion
The break and continue statements are valuable tools for controlling the flow of execution within loops and switch statements in C# programs. They allow programmers to modify the loop's behavior by terminating or skipping iterations based on specific conditions, enabling more precise and efficient program execution.