Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break nested loops

Can someone tell me how to break the main loop when I have nested loops?
Example*:

/*Main loop*/
for(int y = 0; y < 100; y+=10)
{
    /*Sub loop*/
    for (int x = 0; x < 100; x += 10)
    {
        if(x == 60) 
        { 
            //Break the main loop 
        }
    }
}

*This code do nothing, it's just an example

What should I put in the place of the "Break main loop" comment? In java there are labels which I can break (when i set a label to the main loop named "MainLoop" I can write "break MainLoop;" and it will be valid), but what can I do here?

Thanks in advise!

like image 550
Bankin Avatar asked Dec 13 '11 22:12

Bankin


People also ask

How do you break a nested loop in Python?

The outer loop must contain an if block after the inner loop. The if block must check the value of the flag variable and contain a break statement. If the flag variable is True, then the if block will be executed and will break out of the inner loop also.

Can we use break in nested IF?

if is not a loop in any programming language(not in C++ either). If-else statements are conditional statements where you take some actions if a predefined condition is true or false. There is no loop in if statements. So you can't break if statement since it is not a loop or switch statement.

How does break work in nested loops Java?

Break Statement is a loop control statement that is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop.


2 Answers

goto!

I fail to understand this persistent meme which says that goto is considered "harmful". When used correctly, it is very powerful, and this is such a case.

like image 171
fge Avatar answered Nov 15 '22 21:11

fge


Some people would shoot me for suggesting the use of the goto statement, but breaking out of multiple loops is one of the places it can be very useful (and efficient):

/*Main loop*/
for(int y = 0; y < 100; y+=10)
{
    /*Sub loop*/
    for (int x = 0; x < 100; x += 10)
    {
        if(x == 56) 
        { 
            goto MainLoopDone;
        }
    }
}

MainLoopDone:
// carry on here
like image 44
Matt Lacey Avatar answered Nov 15 '22 21:11

Matt Lacey