In C#, break and continue are control flow statements that allow you to alter the execution flow of loops (such as for, while, do-while, and foreach). Both statements are crucial for managing how and when a loop terminates or skips iterations.
break Statement
The break statement terminates the nearest enclosing loop (or switch statement) and transfers control to the statement immediately following the loop or switch. This is particularly useful when you want to exit a loop based on a specific condition.
Example
Let’s consider an example where we use a break statement to exit a for loop when a specific value is encountered in an array.
Initialization: We define an array numbers containing the integers 1 through 9 and set a target value target to 5.
for Loop: The loop iterates over the elements of the numbers array.
Condition Check: Inside the loop, we check if the current element numbers[i] is equal to the target value.
Break on Condition: When the target value is found, the break statement is executed, terminating the loop.
Output: The loop prints numbers up to the target and exits as soon as the target is found.
continue Statement
The continue statement skips the current iteration of the nearest enclosing loop and proceeds with the next iteration. This is useful when you want to skip certain iterations based on a condition without terminating the entire loop.
Example
Let’s consider an example where we use a continue statement to skip even numbers in an array and only process odd numbers.
Initialization: We define an array numbers containing the integers 1 through 12.
for Loop: The loop iterates over the elements of the numbers array.
Condition Check: Inside the loop, we check if the current element numbers[i] is even using the modulus operator %.
Continue on Condition: If the number is even, the continue statement is executed, skipping the rest of the loop body for that iteration.
Output: The loop only processes and prints odd numbers.
Combining break and continue
You can also combine break and continue statements in a single loop to handle more complex control flow scenarios. Here’s an example that demonstrates both break and continue in a loop: