I know it is terribly inefficient and ugly code, but if I have three for
loops, nested inside each other such as so:
for x in range(0, 10):
for y in range(x+1, 11):
for z in range(y+1, 11):
if ...
I want to break the two inner loops and continue to the next iteration of the outer loop if the if
statement is true. Can this be done?
When continue statement is used in a nested loop, it only skips the current execution of the inner loop. Java continue statement can be used with label to skip the current iteration of the outer loop too.
A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.
Answer. Answer: Since the code block of a loop can include any legal C++ statements, you can place a loop inside of a loop.
In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues.
Check some variable after each loops ends:
for x in range(0, 10):
for y in range(x+1, 11):
for z in range(y+1, 11):
if condition:
variable = True
break
#...
if variable:
break;
#...
Another option is to use exceptions instead of state variables:
class BreakException(Exception):
pass
for x in range(0, 10):
try:
for y in range(x+1, 11):
for z in range(y+1, 11):
if True:
raise BreakException
except BreakException:
pass
I imagine this could be especially useful if bailing out of more than two inner loops.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With