🎓 A1Learner
🔍
0 of 52 lessons completed

Julia For Loops

A for loop repeats a block of code once for each item in a collection. The loop variable holds one item at a time, in order.

A for loop visits each item of an array

The loop variable takes each number in the array in order. The body prints it once per round.

for n in [10, 20, 30]
    println(n)
end

A for loop visits each character of a string

Looping over a string gives one character per round. The three characters print on separate lines.

for ch in "Ana"
    println(ch)
end

A function wrap lets a for loop add values up

The adding happens inside a small function defined in the same block. The total after the loop is the sum of all three scores.

function addscores()
    result = 0
    for score in [5, 10, 15]
        result = result + score
    end
    println(result)
end
addscores()

Example

function report()
    tally = 0
    for ch in "Julia"
        tally = tally + 1
    end
    println(tally)
    for word in ["sun", "moon"]
        println(word)
    end
end
report()

Key points

  • For loop: a loop that runs its body once for every item in a collection.
  • Collection: a group of values the loop can visit one by one, such as an array or a string.
  • Loop variable: the name before in holds the current item on each round.
  • Body: the indented lines between the for line and end run once per item.
  • String loop: looping over a string visits its characters one at a time.

In this example, the first loop visits the five characters of the string and counts them in tally. The program prints the count, which is 5. The second loop then visits the two words in the array and prints each one.

Note

Reading values in a loop is fine at the top level, but adding them up needs a function wrap, as the next lessons show.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What is the last value printed by this loop? for x in [2, 4, 6] println(x) end