Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of nested loops?

If I use a break statement, it will only break inner loop and I need to use some flag to break the outer loop. But if there are many nested loops, the code will not look good.

Is there any other way to break all of the loops? (Please don't use goto stmt.)

for (int i = 0; i < 1000; i++) {
   for (int j = 0; j < 1000; j++) {
       if (condition) {
            // both of the loops need to break and control will go to stmt2
       }
   }    
}

stmt2
like image 334
user966379 Avatar asked Sep 26 '22 07:09

user966379


People also ask

How do you break a loop out of a nested loop?

There are two steps to break from a nested loop, the first part is labeling loop and the second part is using labeled break. You must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop.

How do I break out of nested loops in Java?

Java break and Nested Loop In the case of nested loops, the break statement terminates the innermost loop. Here, the break statement terminates the innermost while loop, and control jumps to the outer loop.

How do you break out of a loop in a loop?

Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.


1 Answers

No, don't spoil the fun with a break. This is the last remaining valid use of goto ;)

If not this then you could use flags to break out of deep nested loops.

Another approach to breaking out of a nested loop is to factor out both loops into a separate function, and return from that function when you want to exit.

Summarized - to break out of nested loops:

  1. use goto
  2. use flags
  3. factor out loops into separate function calls

Couldn't resist including xkcd here :)

enter image description here

source

Goto's are considered harmful but as many people in the comments suggest it need not be. If used judiciously it can be a great tool. Anything used in moderation is fun.

like image 243
Srikar Appalaraju Avatar answered Oct 19 '22 15:10

Srikar Appalaraju