Menu
Topics Index
...
`


Control Statements > Jump Statements >
Siva Nookala - 12 Apr 2016
In this example we will print combinations of numbers until the product is less than 15.

Print production combinations till 15
class PrintProductCombinationsTill_15
{
    public static void main(String arg[])
    {
        int number1 = 7;
        int number2 = 4;
        outer : for (int i = 2; i <= number1; i++) // first for loop
        {
            for (int k = 2; k <= number2; k++) // second for loop
            {
                int product = i * k;
                if (product > 15) // LINE A
                    break outer; // LINE B
                System.out.println(i + " x " + k + " = " + product);
            }
        }    
    }
}
OUTPUT

2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
4 x 2 = 8
4 x 3 = 12

DESCRIPTION

Here the outer for loop iterates with i from 2 to 7. For every value of i, the inner loop iterates with k from 2 to 4. When the product is less than 15, the break is not executed. When it is greater than 15, break is executed, hence terminating both the loops.

THINGS TO TRY
  • Comment or remove LINE A in the above program to see a compilation error since, break should be in a if block if it is not the last sentence.
  • If break; is called instead of break outer; at LINE B only the internal loop will be terminated. The outer loop will continue to run which will give the following output.
    2 x 2 = 4
    2 x 3 = 6
    2 x 4 = 8
    3 x 2 = 6
    3 x 3 = 9
    3 x 4 = 12
    4 x 2 = 8
    4 x 3 = 12
    5 x 2 = 10
    5 x 3 = 15
    6 x 2 = 12
    7 x 2 = 14

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.