Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Break and Continue in C#

Introduction

In C# programming, break and continue are control flow statements that alter the execution flow of loops. They are particularly useful for managing the iteration process in loops such as for, while, and do-while loops.

The Break Statement

The break statement is used to exit a loop prematurely. When a break statement is encountered inside a loop, the loop terminates immediately, and control is transferred to the statement following the loop.

Example:

Consider the following for loop that prints numbers from 1 to 10 but exits the loop when the number 5 is encountered:

for (int i = 1; i <= 10; i++)
{
    if (i == 5)
    {
        break;
    }
    Console.WriteLine(i);
}
Output:
1
2
3
4

The Continue Statement

The continue statement skips the remaining code inside the current iteration of the loop and proceeds with the next iteration of the loop. This is useful when you want to skip certain conditions but continue executing the loop.

Example:

Consider the following for loop that prints numbers from 1 to 10 but skips the number 5:

for (int i = 1; i <= 10; i++)
{
    if (i == 5)
    {
        continue;
    }
    Console.WriteLine(i);
}
Output:
1
2
3
4
6
7
8
9
10

Using Break and Continue Together

Sometimes, you might need to use both break and continue statements within the same loop to provide more complex control over the loop execution.

Example:

Consider the following for loop that prints numbers from 1 to 10, skips the number 5, and exits the loop when the number 8 is encountered:

for (int i = 1; i <= 10; i++)
{
    if (i == 5)
    {
        continue;
    }
    if (i == 8)
    {
        break;
    }
    Console.WriteLine(i);
}
Output:
1
2
3
4
6
7

Conclusion

The break and continue statements are powerful tools for controlling the flow of loops in C#. The break statement allows you to exit a loop prematurely, while the continue statement lets you skip the current iteration and proceed with the next one. By understanding and using these statements correctly, you can write more efficient and readable code.