Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I break from the main/outer loop in a double/nested loop? [duplicate]

If I have loop in a loop and once an if statement is satisfied I want to break main loop, how am I supposed to do that?

This is my code:

for (int d = 0; d < amountOfNeighbors; d++) {     for (int c = 0; c < myArray.size(); c++) {         if (graph.isEdge(listOfNeighbors.get(d), c)) {             if (keyFromValue(c).equals(goalWord)) { // Once this is true I want to break main loop.                 System.out.println("We got to GOAL! It is "+ keyFromValue(c));                 break; // This breaks the second loop, not the main one.             }         }     } } 
like image 471
Shepard Avatar asked Oct 25 '12 16:10

Shepard


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 you break an outer loop in Python?

The outer loop must contain an if block after the inner loop. The if block must check the value of the flag variable and contain a break statement. If the flag variable is True, then the if block will be executed and will break out of the inner loop also.

How do you stop a nested loop in Python?

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.


2 Answers

Using a labeled break:

mainloop: for(){  for(){    if (some condition){      break mainloop;    }   } } 

Also See

  • “loop:” in Java code. What is this, and why does it compile?
  • Documentation
like image 181
jmj Avatar answered Sep 18 '22 15:09

jmj


You can add labels to your loop, and use that labelled break to break out of the appropriate loop: -

outer: for (...) {     inner: for(...) {         if (someCondition) {             break outer;         }     } } 

See these links for more information:

  • Branching Statements
  • JLS - Break Statement
like image 25
Rohit Jain Avatar answered Sep 20 '22 15:09

Rohit Jain