Infinite Loop

Break Statement

A break statement exits a loop immediately, regardless of its condition. Execution continues on the first line after the loop.

This page covers the break statement in the context of loops. For an introduction to loops, see Loop.

Breaking Out of a Loop#

The most common use is inside a while loop to stop based on something that happens inside the loop body, rather than the condition at the top:

While Loop

A while loop repeats a block of code as long as a condition is true. Each time the block finishes, the condition is checked again. When it becomes false, the loop stops.

For a broader introduction to loops, see Loop.

  ┌─────────────────┐
  │   check condition│◄──────┐
  └────────┬────────┘        │
      true │  false          │
           ▼      ▼          │
    ┌────────────┐  exit      │
    │ loop body  │───────────┘
    └────────────┘

Basic While Loop#

int count = 0;

while (count < 3)
{
    Console.WriteLine(count);
    count++;
}

Output: 0, 1, 2. When count reaches 3, the condition count < 3 becomes false and the loop stops.