How to break out of exactly the current loop?

Hi all, I know the use of break, which is that a ‘break’ statement inside such a loop exits the entire nest of loops, not just the inner one. What if I just want to exit the inner one?
For instance

for i in 1:5, j in 1:10
       println(i)
       println(j)
       if j == 5
           break
       else 
           continue
       end
end

The upper is a nested loop. How to break the inner loop only? Thanks!

Just separate it out into two for loops:

for i in 1:5
    for j in 1:10
        println(i)
        println(j)
        if j == 5
            break
        else 
            continue
        end
    end
end
1 Like

Thank you for your reply. However, if we consider the following code,

while true
	checkArray = zeros(0)
       #the for-loop will run three times
	for j in 1:3
		#do something to get the result
		result = solve(function1, function2)
		global result
		push!(checkArray, length(result))
	end

	#if the elements in checkArray are not the same, the while-loop will run again.
	if length(unique(checkArray)) == 1
		break
	else 
		continue
    end
	print("hello")
end

‘hello’ will never be output if length(unique(checkArray)) == 1.
Could you please help me solve this?

Looks like you should put the break check inside the j loop if that’s the loop you want to break out of.

1 Like

Oh yeah! Thanks a lot.

1 Like