Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break statement inside two while loops

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.

like image 617
adrian Avatar asked Sep 12 '12 17:09

adrian


People also ask

Can we use break inside while loop?

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.

Does break only break one loop?

A break statement will take you out of the innermost loop enclosing that break statement. In the example the inner while loop. Show activity on this post. The java break statement won't take you out of multiple nested loops.

How do you break a loop inside a 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.


Video Answer


1 Answers

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. } 
like image 163
Abhishekkumar Avatar answered Oct 11 '22 21:10

Abhishekkumar