🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Ranges

A range is a sequence of numbers described by its start and its end. Adding a middle number sets the step between values.

Collect turns a range into a printed array

A range on its own prints in its short form. The collect function builds the full array of numbers.

println(1:5)
println(collect(1:5))

A step range can climb by steps or count down

The first range climbs from 1 by steps of 2. The second range uses a step of -1 and counts down from 5 to 1.

println(collect(1:2:9))
println(collect(5:-1:1))

A range inside a for loop can add numbers up

The loop sits inside a function so it can build a total. Adding the numbers from 1 to 5 gives 15.

function addrange()
    result = 0
    for n in 1:5
        result = result + n
    end
    println(result)
end
addrange()

Example

println(collect(2:2:10))
function countdown()
    for n in 5:-1:1
        println(n)
    end
end
countdown()

Key points

  • Range: a sequence written as start:end, such as 1:5.
  • End included: the last number is part of the sequence, so 1:5 holds five numbers.
  • Step: the middle number in start:step:end sets how far apart the values are.
  • Collect: this function turns a range into an array you can print and use.
  • Countdown range: a negative step counts down, as in 5:-1:1.
  • Loop use: a for loop can visit the numbers of a range one by one.

In this example, the first line collects the even numbers from 2 to 10 and prints them as one array. The function then runs a for loop over the countdown range 5:-1:1. Each number prints on its own line, from 5 down to 1.

Note

A range only describes its numbers, and collect builds the array when you ask for it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does collect(1:3:10) give?