Operators break, continue. Examples of using

Operators break, continue. Examples of using


Contents



1. Operator break. Features of use. General form

The break statement exits the block of curly brackets { } of a loop statement or switch statement and pass control to the next statement in the program. If nested statements are used, the break statement exits the innermost statement.

The general form of the break statement is as follows

break;

2. Statement break with label. Features of using. Keyword goto

The break statement with a label can be used as an analogue of the goto operator, which is present in other programming languages. In the Java language, the goto statement is not used. However, the goto keyword is reserved.

The general form of the break operator with a label is as follows:

break labelName;

here labelName – this is the label that corresponds to the code block. A code block is a set of operators taken in curly brackets { }.

If the program encounters a break statement with a label, then a passing is occured to the label, which must be implemented in the program.

The general form of the label is as follows

labelName: {
    // the sequence of operators
    // ...
}

here labelName – the name of label. The label name is set as well as for any identifier.

3. Which operators can use the break statement?

The break statement can be used in all loop statements and the switch statement. In other words, the break statement cannot be used outside the loop or the switch statement.

4. Operator continue. Features of using. General form

The continue statement is used in loops. The continue statement provides a passing to the next iteration in the loop.

The general form of the continue operator is:

continue;

Most often, the continue statement is called when a certain condition is reached in the body of the loop.

5. Operator continue with label

The continue statement can be implemented with a label. In this case, the general form of the continue statement is as follows

continue labelName;

here labelName – the name of the label that corresponds to the cycle in which the call is implemented using the continue statement.

6. Which operators can use the continue operator?

The continue statement can only be used in loops. In other words, the continue operator cannot be used outside the loop.

7. Examples of solving tasks that use the break statement

Example 1. Determining the presence of a negative number in a one-dimensional array.

// Determining the presence of a negative number in a one-dimensional array
int A[] = { 3, 5, -7, 20, 39, 12 };
boolean f_is = false;

for (int i=0; i<A.length; i++)
    if (A[i]<0) // Is there a negative number in the array?
    {
        f_is = true; // if there is a solution has been found
        break; // exit from loop, further loop execution does not make sense
    }

if (f_is) System.out.println("A negative number is in the array.");
else System.out.println("There is no negative number in the array.");

Example 2. Determining the presence of a given number n in a two-dimensional array of size 2×3. In this example, the break statement is called twice. The first time when you need to exit the inner loop, in which the variable j is an iterator. The second time, when you need to exit the outer loop, in which the variable i is an iterator.

// Determining the presence of a negative number in a one-dimensional array
int A[][] = {
    { 3, 5, -3 },
    { 2, 8, 0 }
};
boolean f_is = false;
int n = 5;

for (int i=0; i<A.length; i++) {
    for (int j=0; j<A[i].length; j++)
        if (A[i][j]==n) {
            f_is = true; // if the number is found, then exit from the inner loop
            break; // further execution does not make sense
        }
        if (f_is) break; // exit from an external loop
    }

if (f_is) System.out.println("The number is in the array.");
else System.out.println("The number is not in the array.");

If a two-dimensional array is large in size, then using the break statement increases the speed of the loop execution.

8. An example of using the break statement with label

The break statement with a label works in the same way as the goto operator in other programming languages. In the Java language, the goto statement is not used. However, the goto keyword is reserved. Instead of goto, is used the break statement with label with some restrictions.

A two-dimensional array of integers is specified. Determine whether there are any negative items in the array. Below is a code fragment that solves this problem.

// The break statement with label
int[][] A = {
                { 2, 5, 8, },
                { 3, -7, 4 },
                { -2, 1, 3 },
                { -4, 2, 3 }
            };
boolean f_is = false;
          
// label named M1
M1:
for (int i=0; i<A.length; i++)
    for (int j=0; j<A[i].length; j++) {
        k++;
        if (A[i][j]<0) {
            f_is = true;
            break M1; // complete the loop, move to the next statement
            // continue M1; - move to the next iteration of the outer loop (counter i)
        }
    }

if (f_is)
    System.out.println("There are positive items in array A");
else
    System.out.println("There are no positive items in array A");

All elements of a two-dimensional array are searched in two nested loops. Before calling cycles is placed label with the name M1. If in the cycle of the lower level (counter j) there is a command

break M1;

then there is an exit from both cycles and transition to the following program operator:

...
if (f_is)
    System.out.println("There are positive items in array A ");
else
    System.out.println("There are no positive items in array A ");

If the label M1 is placed before the if statement, for example:

...
M1:   
if (f_is)
    System.out.println("There are positive items in array A ");
else
    System.out.println("There are no positive items in array A ");

then the java compiler will generate an error

Unresolved compilation problem:
The label M1 is missing

since in a break statement with a label, a label can be placed only before the cycle in which it is used.

9. Examples of tasks solving that use the continue operator

Example 1. Given the number n. Write a code snippet that calculates the following sum S = 2 + 4 + … + 2·n.

There are many ways to solve this problem. In this case, the task is solved using the continue operator.

int s=0;
int n;
n = 10;

for (int i=1; i<=2*n; i++) {
    if (i%2==1) continue; // odd values of i it is needed to skip
    s = s+i; // add only pair values of i
}

In the line

if (i%2==1) continue;

the value of i is checked. If the value of i is odd (i% 2 == 1), then the passing to the next iteration occurs using the continue operator. Thus, only pair values of i are summed.

Example 2. In a given array of numbers, all positive items are multiplied by 2. To solve, use the operator continue.

// the use of continue operator
double[] A = { 3.8, -2.5, 4.6, -1.8, -2.2, 5.6, 1.5 };

// in array A all positive items are multiplied by 2
for (int i=0; i<A.length; i++) {
    // if the array item is negative, then go to the next iteration
    if (A[i]<0)
        continue;

    // otherwise multiply this item by 2
    A[i] = A[i] * 2;
}

10. Examples of solving tasks that use the continue operator with a label

Example 1. The use of the continue statement with a label that is placed in a nested loop (inner loop) is demonstrated. The label is named ‘loop’. In the example is the sum of the elements that are placed on the main diagonal of the matrix A of size 5×5.

// sum the matrix items that are located on the main diagonal
// in these elements, the position in row i is equal to the position in column j
int n = 5; // matrix dimension

double A[][] = {
    { 3.2, 4.1, 2.8, 3.4, 3.4 },
    { 1.3, 4.3, 5.5, 0.4, 1.4 },
    { 3.4, 4.7, 2.1, 3.4, 3.4 },
    { 6.2, 4.1, 2.6, 2.4, 2.4 },
    { 0.7, 7.1, 3.8, 1.4, 4.4 }
};
double summ = 0;

// in the inner loop, a label is declared with the name 'loop'
for (int i=0; i<n; i++)
    loop:
    for (int j=0; j<n; j++) {
        // if not the main diagonal, then go to the next iteration
        if (i!=j) continue loop;
        summ += A[i][j];
    }

Example 2. The use of the continue statement with a label that is located on the outer (upper) loop is demonstrated. The program determines the number of lines in the array A, in which there are negative elements.

// sum the matrix elements that are located on the main diagonal
// in these items, the position in row i is equal to the position in column j
int n = 0; // number of lines with negative items
double A[][] = {
    { 3.2, -4.1, 2.8, 3.4, 3.4, 3.6, 4.8 },
    { 1.3, 4.3, 5.5, 0.4, 1.4, 2.0, 1.0 },
    { 3.4, -4.7, 2.1, -3.4, 3.4, 3.0, 5.5 },
    { 6.2, 4.1, 2.6, 2.4, 2.4, 1.8, 1.9 },
    { -0.7, 7.1, 3.8, 1.4, 4.4, 2.3, 4.0 }
};

// a label is declared with the name nextRow
nextRow:
for (int i=0; i<A.length; i++)
    for (int j=0; j<A[i].length; j++) {
        // if a negative item is found, then move to the next row in the array
        if (A[i][j]<0) {
            n++; // increase the counter
            continue nextRow;
        }
    }

System.out.println("n = " + n); // n = 3

All items of an array are iterated using two nested loops. The variable i is responsible for the row number, the variable j is responsible for the column number.

If at least one negative item is found in the i-th line of the array, then a further search of the elements of this line does not make sense. Need to go to the next line. That is why, here the operator is called continue with a label that is placed on the top (outer loop). The label has the name nextRow.

11. What are the benefits of using break and continue statements in programs?

Using break and continue gives the following advantages:

  • in the case of a cyclic process, there is no need to perform unnecessary iterations if the desired value is found or the desired result is achieved. This gives an increase in the speed of the program execution;
  • at the premature termination of the cyclic process, the code structure is not distorted.

12. What is the difference between a break statement with a label and a continue operator with a label

The break statements with a label and continue with a label can be used only when the program has nested loops. The break statement with a label performs a complete exit from all nested loops. The continue statement with a label exits the current nested loop and goes to the next iteration of the outer loop.


Related topics