#16 – C# break Statement

The break statement terminates the closest enclosing loop or switch statement in which it appears. If it is used in the nested inner loop, it will jump out the inner loop and return the control to the outer loop.

Break Simple Loop

using System;
int i = 0;
while (i < 10)
{
    if(i == 5) break;

    Console.WriteLine($" {i} ");

    i += 1;
}

Output:

 0 
 1 
 2 
 3 
 4 

Break Nested Loop

using System;
int i = 0;
while (i < 10)
{
    int j = 0;

    while (j < i)
    {
        if(j > 5) break;

        Console.Write($" {j} ");

        j += 1;
    }

    Console.WriteLine();

    i += 1;
}

Output:

 0 
 0  1 
 0  1  2 
 0  1  2  3 
 0  1  2  3  4 
 0  1  2  3  4  5 
 0  1  2  3  4  5 
 0  1  2  3  4  5 
 0  1  2  3  4  5 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.