2

I have the following for loop :

for (int i = 0; i<arr.length;i++) {
    for(int j =0; j<someArr.length; j++) {
       //after this inner loop, continue with the other loop
    }
}

I would like to break out of the inner loop and continue the iteration of the outer loop. How do I do this?

Troll PC
  • 85
  • 1
  • 1
  • 7

5 Answers5

2

Generally you can use a combination of lable and break to jump to where you want like this

OUTER_LOOP: for (int i = 0; i<arr.length;i++) {
    for(int j =0; j<someArr.length; j++) {
       //after this inner loop, continue with the other loop
     break OUTER_LOOP;

    }
}

If you want to break to some where in the outer loop you do like this, put the lable where you want to jump to(outside of the current loop) and use that lable in the break statement.

 for (int i = 0; i<arr.length;i++) {
    //line code 1
   OUTER_LOOP: // line code 2
    for(int j =0; j<someArr.length; j++) {
       //after this inner loop, continue with the other loop
     break OUTER_LOOP;

    }
}
The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
1

break does not stop all iterations.

So if you do the following, you will only break out of the nested loop (second for) and continue the current iteration of the first for loop:

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < someArr.length; j++) {
       break;
       // NOT executed after the break instruction
    }
    // Executed after the break instruction
}
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
0

you have to use break; in the inner for-loop. if you use break; the outer for-loop will be automatically continue. Your code will be :-

for (int i = 0; i<arr.length;i++) {
    for(int j =0; j<someArr.length; j++) {
       //after this inner loop, continue with the other loop

       if(condition){
            break; //break out of inner loop
       }
    }
}
0

In case you need this in the future, you can also use a continue statement.

Break will leave the loop, but continue will skip the rest of the code and jump to the next loop iteration. This will be useful if you want to skip some inner loop iterations but continue on the same outerloop iteration.

Like so:

for (int i = ... ) {
    for (int y = ... ) {

    if (some condition) {
        continue;
    }

    // other code here to be executed if some condition is not met

    }
}
0

U can use break

for (int i = 0; i<arr.length;i++) {
    for(int j =0; j<someArr.length; j++) {
       //after this inner loop, continue with the other loop
       break;
    }
// Executed after the break instruction
}