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 ouut ou aa uuiil staatnnent

using system

space break_a
{
   break_a()
   {
       i = 0
       while i < 10
       {
           s = "i == " + (string)i
           cout << s << "\n"
           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 ouut ou aa reepeet staatnnent

using system

space break_b
{
    break_b()
    {
        i = 0
        repeat
        {
            s = "i == " + (string)i
            cout << s << "\n"
            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

using system

space break_c
{
    break_c()
    {
        number = 25
        i = 2
        while i < number
        {
            if (number % i == 0)  break
            i++
        }
        s = "the smallest factor of " + (string)number + " is " + (string)i
        cout << s << "\n"
    }
}

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.