= 0
π while π < 10
+= 1
π println(π)
end
1
2
3
4
5
6
7
8
9
10
while *condition*
*loop body*
end
= 0
π while π < 10
+= 1
π println(π)
end
1
2
3
4
5
6
7
8
9
10
= ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
myfriends
= 1
i while i <= length(myfriends)
= myfriends[i]
friend println("Hi $friend, it's great to see you!")
+= 1
i end
Hi Ted, it's great to see you!
Hi Robyn, it's great to see you!
Hi Barney, it's great to see you!
Hi Lily, it's great to see you!
Hi Marshall, it's great to see you!
for *var* in *loop iterable*
*loop body*
end
for n in 1:10
println(n)
end
1
2
3
4
5
6
7
8
9
10
= ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
myfriends
for friend in myfriends
println("Hi $friend, it's great to see you!")
end
Hi Ted, it's great to see you!
Hi Robyn, it's great to see you!
Hi Barney, it's great to see you!
Hi Lily, it's great to see you!
Hi Marshall, it's great to see you!
or use β
for i β 1:3
println(i)
end
1
2
3
Loop over Index by eachindex()
for i in eachindex(myfriends)
println("No $i, named $(myfriends[i])")
end
No 1, named Ted
No 2, named Robyn
No 3, named Barney
No 4, named Lily
No 5, named Marshall
Now letβs use for loops to create some addition tables, where the value of every entry is the sum of its row and column indices.
= 5, 5
m, n = fill(0, (m, n)) A
5Γ5 Matrix{Int64}:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
typeof(1:10)
UnitRange{Int64}
for j in 1:n
for i in 1:m
= i + j
A[i, j] end
end
A
5Γ5 Matrix{Int64}:
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
6 7 8 9 10
Multiple nested for loops can be combined into a single outer loop, forming the cartesian product of its iterables:
for i = 1:2, j = 3:4
println((i, j))
end
(1, 3)
(1, 4)
(2, 3)
(2, 4)
= 5, 5
m, n = fill(0, (m, n)) B
5Γ5 Matrix{Int64}:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
= 5, 5
m, n for j in 1:n, i in 1:m
= i + j
B[i, j] end
B
5Γ5 Matrix{Int64}:
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
6 7 8 9 10
Multiple containers can be iterated over at the same time in a single for loop using zip
:
for (j, k) in zip([1 2 3], [4 5 6 7])
println((j,k))
end
(1, 4)
(2, 5)
(3, 6)
One line array comprehension
= [i + j for i in 1:n, j in 1:m] C
5Γ5 Matrix{Int64}:
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
6 7 8 9 10
Loop over integers between 1 and 10 and print their squares.
Array Loop
## Create Vector
= fill(0, 10)
D
## Loop
for i in 1:10
= i^2
D[i] end
D
10-element Vector{Int64}:
1
4
9
16
25
36
49
64
81
100
Array Comprehension
= [i^2 for i in 1:10] D
10-element Vector{Int64}:
1
4
9
16
25
36
49
64
81
100
Dict
## Create Empty Dict
= Dict{Int, Int}()
E
## Loop
for i in 1:10
= i^2
E[i] end
E
Dict{Int64, Int64} with 10 entries:
5 => 25
4 => 16
6 => 36
7 => 49
2 => 4
10 => 100
9 => 81
8 => 64
3 => 9
1 => 1
Dict Comprehension
= Dict(i => i^2 for i in 1:10) E
Dict{Int64, Int64} with 10 entries:
5 => 25
4 => 16
6 => 36
7 => 49
2 => 4
10 => 100
9 => 81
8 => 64
3 => 9
1 => 1