Skip to content
AgileLogics
5 min read

for Loops and Ranges

Prerequisites: while loops

A for loop runs once for each item in a collection. The most common collection is a range:

for i in 1:5
    print(i, " ")
end
println()

for i in 0:5:20
    print(i, " ")
end
println()

for i in 10:-3:1
    print(i, " ")
end
println()
1 2 3 4 5
0 5 10 15 20
10 7 4 1
  • start:stop includes both ends.
  • start:step:stop sets the step, which can be negative.
  • in, =, and ∈ all work: for i = 1:5, for i ∈ 1:5.

Looping over collections

fruits = ["apple", "banana", "cherry"]
for fruit in fruits
    println(fruit)
end
for (i, fruit) in enumerate(fruits)
    println(i, ". ", fruit)
end
for (fruit, price) in zip(fruits, [1.2, 0.5, 3.0])
    println(fruit, " costs ", price)
end
apple
banana
cherry
1. apple
2. banana
3. cherry
apple costs 1.2
banana costs 0.5
cherry costs 3.0
  • enumerate gives (index, value) pairs.
  • zip walks several collections side by side.

Nested loops

for i in 1:3, j in 1:3
    print(i * j, j == 3 ? "\n" : "\t")
end
1	2	3
2	4	6
3	6	9

for i in 1:3, j in 1:3 is shorthand for one loop inside another.

Ranges are lazy

r = 1:1_000_000
println(length(r), " ", sum(r), " ", r[end])
println(collect(1:2:9))
println(range(0, 1, length=5))
println(collect(range(0, 1, length=5)))
1000000 500000500000 1000000
[1, 3, 5, 7, 9]
0.0:0.25:1.0
[0.0, 0.25, 0.5, 0.75, 1.0]

A range stores only its start, step, and stop, so 1:1_000_000 uses no memory for its elements. collect turns it into a real array; range(a, b, length=n) makes evenly spaced points.

Practice

Print the multiplication table of 7 from 7 x 1 = 7 to 7 x 10 = 70, then print the sum of all multiples of 3 or 5 below 100.

Show solution
for i in 1:10
    println("7 x $i = $(7i)")
end

function sum_multiples(limit)
    total = 0
    for n in 1:limit-1
        if n % 3 == 0 || n % 5 == 0
            total += n
        end
    end
    return total
end
println(sum_multiples(100))
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
2318