Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking nested loop and main loop [duplicate]

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 only break the for loop. How can I have it so that it breaks both the for and the while loops?

Cheers!

like image 864
MrD Avatar asked Mar 20 '13 14:03

MrD


2 Answers

You can use a labeled break, which redirects the execution to after the block marked by the label:

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

Although in that specific case, a simple break would work because if x == 0 the while will exit too.

like image 97
assylias Avatar answered Oct 19 '22 10:10

assylias


bool done=false;
while(!done && x > 0) {
    for(int i = 5;!done &&  i > 0 ; i++) {
        x = x-2;
        if(x == 0){
            done=true;
            break ;
        }
    }
}
like image 22
Luca Rocchi Avatar answered Oct 19 '22 08:10

Luca Rocchi