Break statement inside two while loops

97,227

Solution 1

In your example break statement will take you out of while(b) loop

while(a) {

   while(b) {

      if(b == 10) {
         break;
      }
   }  
   // break will take you here.
}

Solution 2

It will break only the most immediate while loop. Using a label you can break out of both loops: take a look at this example taken from here


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");
  }
}

Solution 3

Only from the inner one. Use labeled break if you wish to break to specific loop

label1:
for(){
  label2:
  for(){
      if(condition1)
      break label1;//break outerloop

      if(condition2)
      break label2;//break innerloop
  }
}

Also See

Solution 4

while (a) {

   while (b) {

      if (b == 10) {
          break;
      }
   }
}

In the above code you will break the inner most loop where (ie. immediate loop) where break is used.

You can break both the loops at once using the break with label

label1: 
while (a) {

   while (b) {

      if (b == 10) {
          break label1;
      }
   }
}

Solution 5

@Abhishekkumar

Break keyword has it's derived root from C and Assembly, and Break it's sole purpose to passes control out of the compound statement i.e. Loop, Condition, Method or Procedures.

Please refer these...

http://tigcc.ticalc.org/doc/keywords.html#break

http://www.functionx.com/cpp/keywords/break.htm

http://en.wikipedia.org/wiki/Break_statement#Early_exit_from_loops

So, if you want to get out of Two loops at same time then you've to use two Breaks, i.e. one in inner loop and one in outer loop.

But you want to stop both loop at same time then you must have to use exit or return.

Share:
97,227
adrian
Author by

adrian

I've been doing a little bit of everything: android, iphone and now learning titanium!

Updated on June 02, 2021

Comments

  • adrian
    adrian almost 3 years

    Let's say I have this:

    while (a) {
      while (b) {
        if (b == 10) {
          break;
        }
      }
    }
    

    Question: Will the break statement take me out of both loops or only from the inner one? Thank you.