Break the nested loop and the main loop

I have the following code:

int x = 100; //Or some other value while(x > 0) { for(int i = 5; i > 0; i++) { x = x-2; if(x == 0) break; } } 

However, this will break the for loop. How can I use it so that it breaks the for and while loops?

Hooray!

+7
source share
4 answers

You can use a labeled break that redirects execution after the block marked with a label:

 OUTER: while(x > 0) { for(int i = 5; i > 0; i++) { x = x-2; if(x == 0) break OUTER; } } 

Although in this particular case, a simple break will work, because if x == 0 , then it will exit.

+6
source
 bool done=false; while(!done && x > 0) { for(int i = 5;!done && i > 0 ; i++) { x = x-2; if(x == 0){ done=true; break ; } } } 
+1
source

See example

 Outer: for(int intOuter=0; intOuter < intArray.length ; intOuter++) { Inner: for(int intInner=0; intInner < intArray[intOuter].length; intInner++) { if(intArray[intOuter][intInner] == 30) { blnFound = true; break Outer; } } } 
0
source

Try to avoid interruptions, there is always another way to write your own loop so that it does not need it, which is much more “beautiful” and easier to understand if someone else needs to change your code. In your example, a while loop is not needed, but to show you how this is possible:

 while(x > 0) { for(int i = 5; i > 0 && x!=0; i++) { x = x-2; } } 

If x is 0, the for loop will be left. Then your condition will be checked: x is less than 0 (it is zero), so your while loop will also stop executing.

0
source

All Articles