The break operator is used whenever we want to end a loop immediately, even before ending its execution in a natural way. Whenever the break operator is met, the execution of the loop is immediately stopped and the program continues executing the first instruction that follows after the loop.
A loop termination using the break operator can only be performed from within the loop’s body, and only on a iteration of the loop.
Let’s take the following example:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
using
System;
namespace
HelloWorld
{
class
Program
{
static void Main(string[] args)
{
int i = 0;
while (true)
{
i++;
if (i > 10)
break;
Console.WriteLine(i);
}
Console.WriteLine("The loop has ended");
Console.ReadLine();
}
}
}
|
If you pay attention to that code, you will think that while(true) will make the loop run forever, because there will never be a condition to make it stop. However, inside that loop we are incrementing an integer, and use a conditional check that says “if our integer is greater than 10, use the break operator”; which, indeed, aborts the loop and continues the execution with the first instruction that follows after it, as you can see:
The concepts explained in this lesson are also shown visually as part of the following video: