Exit two for loops if true

How would I do 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 cycles should stop, and it should continue to work with other code. This is obviously a simplified example of what I'm trying to accomplish. (In other words, I know that I need to initialize variables, etc.)

+4
source share
5 answers

A good way to exit both loops and avoid any code that may follow the innermost loop is to put the loops in the function and return whatever value you need.

for (x=0;x<3;x++) 
{
    for (y=0;y<3;y++) 
    {
        if (z == 1) 
        {
            return RETURN_VALUE
        }
        //avoids this code
    }
    //and this one too
}
0
source

Assuming you don't need values yand xjust assign them values ​​that both loops will handle:

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

z .

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

Of course, there is a little manual work in this - zit is not updated in the provided code fragment . Of course, it should have been if this code worked.

+2
source
for (x=0;x<3;x++) {
    for (y=0;y<3;y++) {
        if (z == 1) {
            // jump out of the two for loops
            x=y=3; //Set the x and y to last+1 iterating value 
            break; // needed to skip over anything outside the if-condition
        }
     }
}
+2
source

You have a flag and break it

int flag=0;

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

All Articles