Simple for loop question

is there a way to arbitrarily step in a for loop? I don’t see it in the docs. For example:

for i in 1:1000
       println("msg: ", i)
end

but going 2 by 2 or 3 by 3 instead of one at a time. The equivalent of C’s:

for(i = 0; i < 1000; i += 3) ...

or would I use a while loop in those cases?

If I understood you correctly:

for i in 0:3:1000
       println(i)
end
1 Like

0:3:10?

1 Like

You could do

for i in 0:3:999
   ...
end

(using 999 for the upper bound to mimic < 1000, though in this case 0:3:1000 would have the same effect since 1000 is not a multiple of 3). See the : and range documentation and also StepRange.

Of course, you can also write the loop more explicitly:

i = 0
while i < 1000
    ...
    i += 3
end
4 Likes