The break Statement


A break statement may be used to cause the immediate termination of a loop. For example the following program uses a break to break out of a while statement.

// Break1 -- Break Out of a While Statement

using System;

class Program
{
    static void Main()
    {
        int i = 0;
        while (i < 10)
        {
            Console.WriteLine("i = {0}", i);
            i++;
            if (i == 5) break;
        }

    }
}

The program prints the following.

i = 0
i = 1
i = 2
i = 3
i = 4

A common programming construct is an infinite loop with one or more breaks to terminate. The next program does the same as the last using this technique.

// Break2 -- Break Out of an Infinite For Loop

using System;

class Program
{
    static void Main()
    {
        int i=0;
        for (;;)
        {
            Console.WriteLine("i = {0}", i);
            i++;
            if (i == 5) break;
        }

    }
}

The infinite for loop is terminated with a break statment when i reaches 5. The next program finds the smallest factor (not including 1) of a number, using a break statement.

// Break3 -- Smallest Factor using break

using System;

class Program
{
    static void Main()
    {
        int number = 25;
        int i = 2;
        while (i < number)
        {
            if (number % i == 0)  break;
            i++;
            
        }
        Console.WriteLine("Smallest factor of {0} is {1}", number, i);
    }
}

The output is as follows.

Smallest factor of 25 is 5

When the input number is prime, the number itself is returned by the above algorithm.

When a break is encountered in the inner loop of a nested loop, the break only exits the inner loop - the outer loop is unaffected.