Skip to main content

Breaking Loops

The break the statement allows you to terminate a loop prematurely (e.g. while, do while, and for loops)

Diagram of a break

Syntax​

The syntax is really chill:

break;

In practice, you’ll use the break statement to terminate a loop based on a condition prematurely. Typically, the condition is independent of the loop’s condition.

while (expression)
{
if (condition)
{
break;
}
}

Example 1: Stop at a Target Number​

This loop counts up from 0 and stops as soon as it reaches Target.

const int Target = 3;

for (int i = 0; i <= 5; i++)
{
if (i == Target)
{
break; // exit the loop when i reaches 3
}
Console.Write(i + " ");
}

Output:

0 1 2

⚠️ Note: break exits only the innermost loop. In nested loops, the outer loop keeps running.

Resources​

Buschinelli, Mauricio. "break & continue: changing Looping Behaviour" John Abbott College, Fall 2023.

https://www.csharptutorial.net/csharp-tutorial/csharp-break/