Julia Loops
Julia has two loop constructs: for loops, which iterate over a collection or range, and while loops, which repeat as long as a condition holds. break and continue control the flow inside both.
for loops and ranges
A range start:stop or start:step:stop describes a sequence of numbers without storing them all. Both ends are inclusive.
for i in 1:5
print(i, " ")
end
println()
for i in 10:-3:0
print(i, " ")
end
println()
for x in 0:0.25:1
print(x, " ")
end
println()
println(collect(2:2:10), " ", length(1:1000))1 2 3 4 5
10 7 4 1
0.0 0.25 0.5 0.75 1.0
[2, 4, 6, 8, 10] 1000
You can loop over any iterable: arrays, strings, tuples, dictionaries, sets. in, = and ∈ are interchangeable in a for header.
for fruit in ["apple", "pear", "plum"]
println("I like ", fruit)
end
for (i, ch) in enumerate("abc")
println(i, " => ", ch)
end
names = ["Ann", "Ben"]
ages = [31, 27]
for (n, a) in zip(names, ages)
println(n, " is ", a)
endI like apple
I like pear
I like plum
1 => a
2 => b
3 => c
Ann is 31
Ben is 27
Nested loops
Several iteration specifications in one for create nested loops; the rightmost varies fastest. A break here leaves all of them.
for i in 1:3, j in 1:3
print(i * j, j == 3 ? "\n" : "\t")
end
for i in 1:3, j in i:3
print("(", i, ",", j, ") ")
end
println()1 2 3
2 4 6
3 6 9
(1,1) (1,2) (1,3) (2,2) (2,3) (3,3)
while loops
# How many times can 1000 be halved before dropping below 1?
n = 1000.0
steps = 0
while n >= 1
global n /= 2
global steps += 1
end
println(steps, " steps, n = ", n)
# Collatz sequence from 6
function collatz(x)
seq = [x]
while x != 1
x = iseven(x) ? x ÷ 2 : 3x + 1
push!(seq, x)
end
return seq
end
println(collatz(6))10 steps, n = 0.9765625
[6, 3, 10, 5, 16, 8, 4, 2, 1]
The global keyword is needed because the loop modifies global variables at the top level of a script. Inside a function (like collatz) it isn't needed. The Scope lesson explains the rule.
break and continue
for n in 1:20
n % 2 == 0 && continue # skip even numbers
n > 9 && break # stop entirely after 9
print(n, " ")
end
println()
# Find the first square number above 50
k = 1
while true
if k^2 > 50
println("first square above 50: ", k^2)
break
end
global k += 1
end1 3 5 7 9
first square above 50: 64
Loop variables are local
A for loop creates a fresh variable on every iteration, local to the loop body. After the loop it no longer exists (unless a variable with the same name already existed outside, inside a function):
function sum_to(n)
total = 0
for i in 1:n
total += i
end
return total
end
println(sum_to(100))
for i in 1:2 end
println(isdefined(Main, :i))5050
false
Iterating with an index
eachindex(a) gives the valid indices of an array, which is safer than 1:length(a) and works for any array type. Use pairs to get index–value pairs:
temps = [12.5, 15.0, 9.5]
for i in eachindex(temps)
temps[i] = round(temps[i] * 9 / 5 + 32, digits=1)
end
println(temps)
for (i, t) in pairs(temps)
println("day ", i, ": ", t, "°F")
end[54.5, 59.0, 49.1]
day 1: 54.5°F
day 2: 59.0°F
day 3: 49.1°F
Test yourself
How many numbers does 1:2:9 contain?
- 4
- 5
- 9
- 8
What does continue do inside a loop?
- Leaves the loop
- Skips to the next iteration
- Restarts the loop from the beginning
- Pauses the program
In for i in 1:2, j in 1:3, which variable changes fastest?
- i
- j
- both equally
- it is random