Hi,

for(i=0;i<10;i++)
{
   for(j=0;j<10;j++)
   {
       if()
       {
       Now I want to exit from j loop and continue from i loop.
       }
       And now if it is wrong I want to continue from j loop.
   }
}

Actually I tried break in if statement but it did not help.

break is the right way.. but keep in mind that you can only break from 1 loop.

for( int i = 0; ...; ...) {
     for( int j = 0; ...; ... ) {
         if( something ) break;
         // You don't need to explicitly continue here, since it is the end of the j loop.. but if something else is coming, and you want to start from the beginning of j write:
         continue;
     }
}

break is the right way.. but keep in mind that you can only break from 1 loop.

for( int i = 0; ...; ...) {
     for( int j = 0; ...; ... ) {
         if( something ) break;
         // You don't need to explicitly continue here, since it is the end of the j loop.. but if something else is coming, and you want to start from the beginning of j write:
         continue;
     }
}

I do not want to enter the j loop second time. After first time just continue from next i.

But your continue affects the j loop and increases j right ?

Use the "break;" that thelamb was suggesting. That will take you out of the j loop, but anything remaining within the i loop at the end will be executed. Then control will go back to the top of the i loop. There will be a fresh j loop at that point. You can experiment with it in your code and output i and j at each step to see these things.

Edited 5 Years Ago by jonsca: n/a

If you're saying that you want to exit the J loop at that point and not enter it again, you could always add a bool statement and check on it before each j loop execution.

Or you could use the notorious jump statement. But since everyone hates it for good reasons, use what Red Goose wrote. In the i loop, after the j loop, and an if to check if a bool is set to true, if this is true then break another time to get out of the i loop. This bool is set in the j loop as you might have guessed.

for(i)
{
	for(j)
		{
			if ()
			{
					for()
					{
					something
					}
				break;
			}
		}
}

actually it worked one time in j loop and stopped. (Didn't pass second i value)

for(i=0;i<10;i++)
{
	for(j=0;j<10;j++)
		{
			if (a>b)
			{
                        cout << "a>b";
					for(k=0;k<10;k++)
					{
					cout <<k;
					}
		        break;
			}
		}
}

I mean if a>b then I want to stop j cycle (after cout k values) and increase i. If it is not I want to increase j until a>b. But in this code it just enters the both loop one time and program stops !

This article has been dead for over six months. Start a new discussion instead.