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.

// break_a -- break out of a while statement

generic break_a
{
    break_a()
    {
        i = 0
        while i < 10
        {
            s = "i == " + i.to_string()
            s.println()
            i++
            if i == 5 break
        }
    }
}

The program prints the following.

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

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

// break_b -- break out of a repeat statement

generic break_b
{
    break_b()
    {
        i = 0
        repeat
        {
            s = "i == " + i.to_string()
            s.println()
            i++
            if i == 5 break
        }
    }
}

The infinite repeat 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.

// break_c -- smallest factor using break

generic break_c
{
    break_c()
    {
        number = 25
        i = 2
        while i < number
        {
            if (number % i == 0)  break
            i++
        }
        s = "the smallest factor of " + number.to_string() + " is " + i.to_string()
        s.println()
    }
}

The output is as follows.

the smallest factor of 25 is 5

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

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.