Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit two for loops if value is true [duplicate]

Tags:

c

loops

How would I accomplish the following?

for (x=0;x<3;x++) {
    for (y=0;y<3;y++) {
        if (z == 1) {
            // jump out of the two for loops
        }
     }
}
// go on to do other things

If z=1, both for loops should stop and it should continue on with some other code. This obviously is an oversimplified example of what I'm trying to accomplish. (In other words, I know I need to initialize variables, etc...)

like image 916
codedude Avatar asked Dec 26 '22 18:12

codedude


2 Answers

Assuming you don't need the values of y and x, just assign them the values that will case both loops to exit:

for (x=0;x<3;x++) 
{
    for (y=0;y<3;y++) 
    {
        if (z == 1) 
        {
           y = 3 ;
           x = 3 ;
        }
     }
}
like image 149
this Avatar answered Dec 28 '22 06:12

this


Add z to your outermost conditional expression, and break out of the innermost loop.

for(x = 0; x < 3 && z != 1; x++) {
    for(y = 0; y < 3; y++) {
        if(z == 1) {
            break;
        }
     }
 }

Of course, there's a fair bit of handwaving involved - in the code snippet you've provided, z isn't being updated. Of course, it'd have to be if this code was to work.

like image 38
Makoto Avatar answered Dec 28 '22 06:12

Makoto