🎓 A1Learner
🔍
0 of 52 lessons completed

Julia While Loops

A while loop repeats a block of code while its condition stays true. The loop ends as soon as the condition becomes false.

A while loop counts up to a limit

The counter starts at 1 and grows by 1 each round. The loop stops when the counter passes 3.

function countup()
    n = 1
    while n <= 3
        println(n)
        n = n + 1
    end
end
countup()

A while loop can count down

The counter starts at 3 and shrinks by 1 each round. When it reaches 0 the condition fails and the final word prints.

function countdown()
    n = 3
    while n > 0
        println(n)
        n = n - 1
    end
    println("Go!")
end
countdown()

A while loop can build up a total

The loop adds each counter value into a running total. After four rounds the total holds the sum of 1 to 4.

function addup()
    result = 0
    n = 1
    while n <= 4
        result = result + n
        n = n + 1
    end
    println(result)
end
addup()

Example

function showevens()
    n = 2
    result = 0
    while n <= 8
        println(n)
        result = result + n
        n = n + 2
    end
    println("Total: $result")
end
showevens()

Key points

  • While loop: a loop that repeats its body as long as the condition after while is true.
  • Condition check: Julia tests the condition before every round of the loop.
  • Loop counter: a variable that tracks progress and is changed inside the body.
  • Progress step: the body must move the counter toward the end, or the loop never stops.
  • Function wrap: putting the loop inside a function keeps its changing variables local to that function.

In this example, the counter n starts at 2 and the total starts at 0. Each round prints n, adds it to the total, and raises n by 2. The loop ends when n passes 8. The last line prints the total of the even numbers, which is 20.

Note

The loops in this lesson sit inside functions, because a top-level while loop cannot safely change a variable made outside it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

A while loop starts with n = 5 and the condition n < 3. How many times does its body run?