How to Break Out of Multiple Loops

How to break out of nested loops?

Use:

if (condition) {
i = j = 1000;
break;
}

How can I break out of multiple loops?

My first instinct would be to refactor the nested loop into a function and use return to break out.

How to break out of nested loops in Go?

use function

package main

import (
"fmt"
)

func getWord() string {
word := ""
for word != "DC" {
for _, i := range "ABCDE" {
for _, j := range "ABCDE" {
word = string(i) + string(j)
fmt.Println(word)
if word == "DC" {
return word
}
}
}
}
return word
}

func main(){
word := getWord()
}

Edit: thanks to @peterSO who points on some mistakes in the details and provides this playground https://play.golang.org/p/udcJptBW9pQ

How do I break out of nested loops in Java?

Like other answerers, I'd definitely prefer to put the loops in a different method, at which point you can just return to stop iterating completely. This answer just shows how the requirements in the question can be met.

You can use break with a label for the outer loop. For example:

public class Test {
public static void main(String[] args) {
outerloop:
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break outerloop;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");
}
}

This prints:

0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
Breaking
Done

Breaking out of nested loops

It has at least been suggested, but also rejected. I don't think there is another way, short of repeating the test or re-organizing the code. It is sometimes a bit annoying.

In the rejection message, Mr van Rossum mentions using return, which is really sensible and something I need to remember personally. :)

Does the break statement break out of multiple loops?

break; only breaks from the innermost loop or switch body it appears in.

If you intend to break from nested loops, you might consider moving the nested loops to a separate function and using return to exit the function from any point inside its body.

Example:

    ...
int matrix[ROWS][COLS];
int value;
...
int found = 0;
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
if (matrix[row][col] == value) {
found = 1;
break;
}
}
if (found)
break;
}
...

Can be simplified as:

int hasvalue(int matrix[ROWS][COLS], int value) {
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
if (matrix[row][col] == value)
return 1;
}
}
return 0;
}

...
int matrix[ROWS][COLS];
int value;
...
found = hasvalue(matrix, value);
...

Can I use break to exit multiple nested 'for' loops?

AFAIK, C++ doesn't support naming loops, like Java and other languages do. You can use a goto, or create a flag value that you use. At the end of each loop check the flag value. If it is set to true, then you can break out of that iteration.

Python - `break` out of all loops

You should put your loops inside a function and then return:

def myfunc():
for i in range(1, 1001):
for i2 in range(i, 1001):
for i3 in range(i2, 1001):
if i*i + i2*i2 == i3*i3 and i + i2 + i3 == 1000:
print i*i2*i3
return # Exit the function (and stop all of the loops)
myfunc() # Call the function

Using return immediately exits the enclosing function. In the process, all of the loops will be stopped.

What's the best way to break from nested loops in JavaScript?

Just like Perl,

loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}

as defined in EMCA-262 section 12.12. [MDN Docs]

Unlike C, these labels can only be used for continue and break, as Javascript does not have goto.



Related Topics



Leave a reply



Submit