在 Julia 中,while 循环用于重复执行语句块,直到满足给定条件。并且当条件变为假时,程序中紧接在循环之后的行被执行。如果第一次执行 while 循环时条件为假,则永远不会执行循环体。 句法 :
while expression
statement(s)
end
这里,’ while ‘是开始while循环的关键字,’ expression ‘是要满足的条件,’ end ‘是结束while循环的关键字。
注意:代码块是包含在条件语句和“结束”语句之间的一组语句。
示例 1:
# Julia program to illustrate
# the use of while loop
# Declaring Array
Array = ["Geeks", "For", "Geeks"]
# Iterator Variable
i = 1
# while loop
while i <= length(Array)
# Assigning value to object
Object = Array[i]
# Printing object
println("$Object")
# Updating iterator globally
global i += 1
# Ending Loop
end
输出:
示例 2:
# Julia program to generate
# the Fibonacci sequence
# The length of Fibonacci sequence
length = 15
# The first two values
a = 0
b = 1
# Iterator Value
itr = 0
# while loop condition
while itr < length
# Printing fibonacci value
print(a, ", ")
# Updating value
c = a + b
# Modify values
global a = b
global b = c
# Updating iterator
global itr += 1
# End of while loop
end