Search code examples
loopsfor-loopjuliadecrement

How to implement a decrementing for loop in Julia?


I know that in python I can do something as follows.

for i in range(10, 0, -1):
    print(i)

Which will output:

10
9
8
7
6
5
4
3
2
1 

I'm very much new to julia and I know I can create normal loops as follows.

for i=1:10
    println(i)
end

Intuitively, I tried something like as follows (since I thought it behaved similar to python's range([start], stop[, step]) function).

for i=10:1:-1
    println(i)
end

Although it didn't fail, it didn't print anything either. What am I doing wrong?

Is there an intuitive way to loop backwards in julia?


Solution

  • Try this:

    julia> for i=10:-1:1
               println(i)
           end
    10
    9
    8
    7
    6
    5
    4
    3
    2
    1
    

    or this

    julia> for i=reverse(1:10)
               println(i)
           end
    10
    9
    8
    7
    6
    5
    4
    3
    2
    1
    

    As @phipsgabler noted you can also use:

    julia> range(10, 1, step=-1)
    10:-1:1
    

    to get the same result again (note though that you have to use 1 as a second index).

    From my practice range is usually more useful with with length keyword argument:

    julia> range(10, 1, length=10)
    10.0:-1.0:1.0
    

    (notice that in this case you get a vector of Float64 not Int)