Skip to content
AgileLogics
4 min read

while Loops

Prerequisites: if statements

A while loop repeats as long as its condition is true:

function countdown(n)
    while n > 0
        print(n, " ")
        n -= 1
    end
    println("liftoff!")
end

countdown(5)
5 4 3 2 1 liftoff!

Make sure something inside the loop eventually makes the condition false, or the loop runs forever (press Ctrl + C to stop it).

break and continue

  • break leaves the loop immediately.
  • continue skips to the next iteration.
function first_square_over(limit)
    n = 1
    while true
        if n^2 > limit
            break
        end
        n += 1
    end
    return n
end

println(first_square_over(50))

function odd_numbers(max)
    n = 0
    while n < max
        n += 1
        iseven(n) && continue
        print(n, " ")
    end
    println()
end

odd_numbers(10)
8
1 3 5 7 9

A classic: the Collatz sequence

function collatz_steps(n)
    steps = 0
    while n != 1
        n = iseven(n) ? n ÷ 2 : 3n + 1
        steps += 1
    end
    return steps
end

println(collatz_steps(6))
println(collatz_steps(27))
8
111

The loops in these examples are inside functions. That's the normal style in Julia — the lesson on scope explains the one surprise you can hit with loops at the top level of a script.