Understanding and Using the C# `break` Statement for Loop Control
Master the C# `break` statement for controlling loop execution. This tutorial explains how `break` terminates `for`, `while`, `do-while`, and `switch` statements prematurely, providing clear examples and demonstrating its behavior in nested loops. Write more efficient and predictable C# code.
Understanding and Using the C# `break` Statement
Introduction
The `break` statement in C# is a control flow statement that terminates a loop (for
, while
, do-while
) or a switch
statement prematurely. It alters the normal sequential execution of your code.
Syntax
The syntax is simple:
`break` Statement Syntax
break;
Example 1: `break` in a Single Loop
This example demonstrates how `break` exits a for
loop when the counter reaches 5.
Example 1: Single Loop
using System;
public class BreakExample {
public static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
Console.WriteLine(i);
}
}
}
Output Example 1
1
2
3
4
Example 2: `break` in Nested Loops
In nested loops, `break` only exits the innermost loop where it's placed.
Example 2: Nested Loops
using System;
public class BreakExample {
public static void Main(string[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break; // Exits only the inner loop
}
Console.WriteLine(i + " " + j);
}
}
}
}
Output Example 2
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Conclusion
The `break` statement is a valuable tool for controlling loop execution. Understanding its behavior, especially in nested loops, is key to writing efficient and predictable C# code.