For in Julia

Julia provides several ways to create loops. Let’s explore the different types of loops available.

# The most basic type, with a single condition.
i = 1
while i <= 3
    println(i)
    global i += 1
end

# A classic initial/condition/after loop.
for j in 0:2
    println(j)
end

# Another way of accomplishing the basic "do this N times" iteration.
for i in 0:2
    println("range ", i)
end

# Julia's `while true` loop will run repeatedly
# until you `break` out of the loop or `return` from
# the enclosing function.
while true
    println("loop")
    break
end

# You can also `continue` to the next iteration of the loop.
for n in 0:5
    if n % 2 == 0
        continue
    end
    println(n)
end

When you run this script, you’ll see the following output:

1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Julia, the for loop is more flexible and can iterate over any iterable object. The while loop is used when you need a condition-based loop. The break and continue statements work similarly to other languages, allowing you to control the flow within loops.

We’ll see some other loop forms later when we look at comprehensions, generators, and other data structures.