When to ‘break’ and When to ‘continue’

There are a couple of ways to interrupt a loop: we’ll explore break and continue.

break

In the following example, a loop-continuation-condition is set to test if the number is less than 20. If true, the number variable will increment by one and the current value of the variable number will be added to the total as is defined by the variable sum.

So if we let the following loop continue without any sort of interruption, the number will be 20 and the sum will be 210.

However, adding the keyword break after the test is performed within the while loop will cause the loop to stop if the sum is at or larger than 100.

The output for the number variable will be 14 and for the sum variable, 105.

/**
 * By: Dino Cajic
 * Adopted from: Introduction to Java Programming
 */
public class TestBreak {
    public static void main(String[] args){
        int sum = 0;
        int number = 0;

        while (number < 20){
            number++;
            sum += number;
            if (sum >= 100){
                break;
            }
        }

        System.out.println("The number is " + number);
        System.out.println("The sum is " + sum);
    }
}
  1. The integer variables are initialized to 0: sum and number.
  2. The while loop starts on line 12. It checks to see if the value inside of the number variable is less than 20. If it is, it enters the loop body.
  3. The number variable is incremented and added to the sum variable.
  4. A check is performed to see if the current value inside of the sum variable is greater than or equal to 100.
  5. While the number variable is less than 13, the value inside of the sum variable will be less than 100. When number = 14, the sum variable will be 105. As soon as that occurs, the conditional evaluates to true and the break command is called, terminating the while loop.
  6. The values in the number and sum variables are displayed on lines 20 and 21.

continue

The next example deals with the keyword continue.

We start the loop by testing whether the number is less than 20. If so, the number variable is incremented by 1. The next condition that it checks is whether the number variable is set to 10 or 11. If so, the continue keyword causes the loop to skip any of the code following the condition and restarts from the beginning of the loop, testing whether the variable number is less than 20. In this case, neither 10 nor 11 will be added to the sum.

If the code executed without the continue keyword, sum would be equal to 210.

However, due to the test and the continue keyword being executed prior to sum, the output will be 189.

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 = 189

 

Leave a Reply