The break statement

Sometimes, it is convenient to stop the loop repetition inside the loop when a certain condition is reached. This can be done with the break statement, which is as follows:

a = 10; b = 150 
while a < b 
    # process(a) 
    println(a) 
    global a += 1 
    if a >= 50                break     end 
end

This prints out the numbers 10 to 49, and then exits the loop when break is encountered. The following is an idiom that is often used; how to search for a given element in an array, and stop when we have found it:

arr = rand(1:10, 10) 
println(arr) 
# get the index of search in an array arr: 
searched = 4 
for (ix, curr) in enumerate(arr) 
  if curr == searched 
    println("The searched element $searched occurs on index $ix") 
    break 
  end 
end 

A possible output might ...

Get Julia 1.0 Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.