Julia Break and Continue
Break and continue are statements that change how a loop runs. Break ends the loop at once, and continue skips ahead to the next round.
Break stops a loop before the later items
The loop prints numbers until it meets 9. The break leaves the loop, so 9 and 4 never print.
for n in [3, 7, 9, 4]
if n == 9
break
end
println(n)
end
println("Stopped")Continue skips one item and keeps going
When the loop meets 3, the continue jumps to the next round. The other numbers still print.
for n in [1, 2, 3, 4]
if n == 3
continue
end
println(n)
endBreak can end a while loop early
The while loop sits inside a function and counts up. The break fires when the counter reaches 4, long before the limit of 10.
function findstop()
n = 1
while n <= 10
if n == 4
break
end
println(n)
n = n + 1
end
println("Done at $n")
end
findstop()Example
function scan()
result = 0
for n in [5, -1, 8, 0, 6]
if n == 0
break
end
if n < 0
continue
end
result = result + n
println(n)
end
println(result)
end
scan()Key points
- Break: this statement leaves the loop at once, and no more rounds run.
- Continue: this statement skips the rest of the current round and starts the next one.
- Trigger check: both statements usually sit inside an if block that tests the current item.
- After break: the code below the loop still runs as normal.
- Skipped work: lines after a continue in the same round do not run for that item.
In this example, the loop inside scan visits each number in the array. The value -1 is skipped by continue, so it is never added or printed. The value 0 triggers break, so 6 is never reached. The program prints the two kept numbers and then their total, 13.
Note
Break ends only the loop it sits in, and the rest of the program carries on.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does continue do inside a loop?