The Break and Continue Statement
In C#, control flow refers to the order in which statements are executed in a program. It determines how the program progresses from one statement to another. Control flow can be modified using various control flow statements, such as the “break” and “continue” statements.
- The “break” statement: The “break” statement is used to exit a loop or switch statement prematurely. When encountered within a loop (such as a “for” or “while” loop) or a switch statement, the “break” statement immediately terminates the loop or exits the switch statement, and the program continues with the next statement after the loop or switch.
Here’s an example of using the “break” statement in a “for” loop:
csharpCopy codefor (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
In this example, the loop iterates from 1 to 10. When i
becomes 5, the “if” condition is true, and the “break” statement is executed, causing the loop to terminate. As a result, only the numbers 1, 2, 3, and 4 will be printed.
- The “continue” statement: The “continue” statement is used to skip the rest of the statements within a loop and move on to the next iteration. When encountered, it jumps to the next iteration of the loop without executing the remaining statements in the current iteration. It is typically used to bypass certain iterations based on a specific condition.
Here’s an example of using the “continue” statement in a “for” loop:
csharpCopy codefor (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue;
}
Console.WriteLine(i);
}
In this example, the loop iterates from 1 to 5. When i
becomes 3, the “if” condition is true, and the “continue” statement is executed. As a result, the WriteLine statement is skipped for that iteration, and the loop continues with the next iteration. The output will be 1, 2, 4, and 5.
Both the “break” and “continue” statements provide ways to alter the normal control flow of a program. They can be powerful tools for controlling loops and making decisions based on specific conditions in C#.
Apply for C Sharp Certification Now!!
https://www.vskills.in/certification/Certified-C-sharp-Professional