Code

break Statement

The break keyword causes the program to exit a loop prematurely, before it has completed its execution.

In the following example, the break statement exits loop B and returns control back to loop A.

Nested loop break statement

In the below code, notice that the loop ends prematurely at break statement when the counter reaches 3 == 3.

for (int counter = 1; counter <= 4; counter ++)
{
    if (counter == 3) // <- A 
        break;

    Console.WriteLine(counter);
}

Run Demo

OUTPUT

1
2

foreach loop :

int[] integerValues = { 1, 2, 3, 4 };

foreach (int value in integerValues)
{
    if (value == 3) // <- A
        break;

    Console.WriteLine(value);
}

Run Demo

OUTPUT

1
2

while loop :

int counter = 0;
while (counter < 4)
{

    counter++;
    if (counter == 3) // <- A
        break;

    Console.WriteLine(counter);
}

Run Demo

OUTPUT

1
2

do-while loop :

int counter = 0;
do
{

    counter++;
    if (counter == 3) // <- A
        break;

    Console.WriteLine(counter);

} while (counter < 4);

Run Demo

OUTPUT

1
2

Add Comment

Click here to post a comment

Subscribe

Most Popular

Popular Video