C# ยท Chapter 20 of 46

C# Break & Continue

The break statement immediately exits a loop or switch statement, stopping further iterations. The continue statement skips the rest of the current iteration and moves to the next one.

Both are useful for controlling loop flow in more complex scenarios, such as stopping a search once a match is found, or skipping invalid data while processing a collection.

Syntax
break;
continue;

break

break immediately stops the loop entirely, and execution continues with the code right after the loop. It's often used once a desired result has been found.

continue

continue skips the remaining code in the current iteration and jumps to the next one, without exiting the loop entirely.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    for (int i = 0; i < 10; i++) {
      if (i == 3) {
        break;
      }
      Console.WriteLine(i);
    }
  }
}
Output
0
1
2

The loop stops entirely once i equals 3, thanks to break.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    for (int i = 0; i < 5; i++) {
      if (i == 2) {
        continue;
      }
      Console.WriteLine(i);
    }
  }
}
Output
0
1
3
4

When i equals 2, continue skips printing and moves to the next iteration.

Key points

  • break exits the loop entirely.
  • continue skips only the current iteration.
  • Both work inside for, while, and do-while loops.
  • break also exits a switch statement's current case.
๐Ÿ’ก Note: Overusing break and continue can make loops harder to follow; use them sparingly and with clear intent.

๐Ÿ“ Quick Quiz

1. What does break do inside a loop?

2. What does continue do inside a loop?

3. Can break be used inside a switch statement?