If I use break
like the code below, then the loop within row
won't iterate the rest if there is a match in the beginning, but what about the col
loop?
Would it still iterate between 0 and 7? Is there a way to use break
there as well?
for (int col = 0; col < 8; col ++) for (int row = 0; row < 8; row ++) if (check something) { //Then do this; break; }
You can break from all loops without using any label: and flags.
Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs.
You can break all loops with else and continue . The code with explanation is as follows. When the inner loop ends normally without break , continue in the else clause is executed. This continue is for the outer loop, and skips break in the outer loop and continues to the next cycle.
One option is to use a condition flag. You could then either break in the outer loop as well, or just use it as an extra condition within the for
loops:
bool keepGoing = true; for (int col = 0; col < 8 && keepGoing; col++) { for (int row = 0; row < 8 && keepGoing; row++) { if (something) { // Do whatever keepGoing = false; } } }
In Java, you can specify a label to break to though. (I didn't see that this question was tagged Java as well as C#.)
outerLoop: for (...) { for (...) { if (...) { break outerLoop; } } }
EDIT: As noted in comments, in C#, you could use a label and goto
:
for (...) { for (...) { if (...) { goto endOfLoop; } } } endOfLoop: // Other code
I'd really recommend that you don't take either of these approaches though.
In both languages, it would usually be best to simply turn both loops into a single method - then you can just return from the method:
public void doSomethingToFirstOccurrence() { for (...) { for (...) { if (...) { return; } } } }
Yes, it is possible by using a break
label:
package others; public class A { public static void main(String[] args) { outer: for(int col = 0; col < 8; col ++) { for (int row = 0; row < 8; row ++) { if (col == 4) { System.out.println("hi"); break outer; } } } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With