The break and continue statements in LOOPS

  1. First, recall the break statement was used in the switch statement: click here

    Effect: the break statement will terminate the switch statement.

  2. The break statement can also be use in while loops, for loops and do loops.

    Effect: the break statement will cause the loop statement to terminate immediately.

    Example: for loop with a break statement
          int i;
    
          for (i = 1; i <= 20; i = i + 1)
          {
             if (i == 12)
                break;
    
             System.out.print (num);
          }
    

    Output:   1   2   3   4   5   6   7   8   9   10   11

    The for loop will run i from 1 to 12. When i = 12, the break statement will cause the for loop to end immediately.

    DEMO program that uses the break statement in a loop (test if a number is prime): click here

    Same DEMO program that DO NOT use the break statement in the loop: click here

     

  3. The continue statement can only be use inside while loops, for loops and do loops.

    Effect: the break statement will cause the loop statement to start a NEW interation immediately

    Example: for loop with a continue statement
          int i;
    
          for (i = 1; i <= 20; i = i + 1)
          {
             if (i == 12)
                continue;
    
             System.out.println ("num is " + num);
          }
    

    Output:   1   2   3   4   5   6   7   8   9   10   11   13   14   15   16   17   18   19   20

    The for loop will run i from 1 to 20. When i = 12, the continue statement will cause the for loop to start a new iteration, skipping the print statement.

    DEMO program that uses the continue statement in a loop (test if a number is perfect): click here

    Same DEMO program that DO NOT use the continue statement in the loop: click here