4

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...)

Ramchandra Apte
  • 4,033
  • 2
  • 24
  • 44
codedude
  • 6,244
  • 14
  • 63
  • 99

5 Answers5

5

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 ;
        }
     }
}
this
  • 5,229
  • 1
  • 22
  • 51
2

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.

Makoto
  • 104,088
  • 27
  • 192
  • 230
2
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
        }
     }
}
Zac Howland
  • 15,777
  • 1
  • 26
  • 42
P0W
  • 46,614
  • 9
  • 72
  • 119
  • Added the needed break in the conditional block. It is needed in the case where there is something after the if-condition that does something (since he is wanting to break out of it at this point). – Zac Howland Oct 26 '13 at 06:34
1

Have 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;
 }
Kumareshan
  • 1,311
  • 8
  • 8
0

A good way to exit both loops and avoid any code that might follow the most inner loop is to put the loops in a function and return any value that 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
}
this
  • 5,229
  • 1
  • 22
  • 51
  • Say I had multiple if statements like the one above inside the for loops. If the first if statement was true and it returned some value would it then skip the next if statements? – codedude Oct 26 '13 at 18:14
  • 1
    When the function returns a value the function exits. – this Oct 27 '13 at 07:11