官术网_书友最值得收藏!

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 be as follows:

[8,4,3,6,3,5,4,4,6,6] 
The searched element 4 occurs on index 2 

The break statement can be used in for loops as well as in while loops. It is, of course, mandatory in a while true...end loop.

主站蜘蛛池模板: 鄢陵县| 甘肃省| 新宁县| 施甸县| 荣昌县| 咸丰县| 盐边县| 黑水县| 会理县| 德安县| 奎屯市| 昭通市| 军事| 元谋县| 金坛市| 普宁市| 兴和县| 阿坝县| 阿拉尔市| 神农架林区| 巴南区| 常德市| 弥勒县| 浮山县| 绍兴县| 瓮安县| 岫岩| 宜昌市| 南开区| 若羌县| 巴彦淖尔市| 博乐市| 纳雍县| 浠水县| 潞城市| 互助| 临泽县| 兰州市| 宁乡县| 颍上县| 阿城市|