4

In Python, we could iterate using a for-loop and skip the indices using the skip parameter as such:

max_num, jump = 100, 10
for i in range(0, max_num, jump):
    print (i)

I could achieve the same with a while loop by doing this:

max_num, jump = 100, 10
i = 0
while i < max_num
    print(i)
    i+=jump
end

And using the same i+=jump syntax shown below in the for-loop doesn't skip the index:

for i in range(0,max_num)
    print(i)
    i+=jump
end

Within a for-loop is "skipping" possible? If so, how?

Nat Gillin
  • 233
  • 2
  • 8

4 Answers4

9

You can just do

max_num, step = 100, 10

for i in 0:step:max_num
    println(i)
end

Using range(), you do not specify max_num, but the desired number of iterations. So 0:step:max_num equals range(0, step, max_num/step).

Toterich
  • 585
  • 2
  • 7
3

The syntax is a little bit different in Julia.

It's range(start, [step,]length) , e.g.

for i in range(0, 3, 10)
   println(i)
end

[out]:

0
3
6
9
12
15
18
21
24
27

There's another syntax start:step:max_num see @Sayse 's answer for detali

ymonad
  • 11,710
  • 1
  • 38
  • 49
1

You do it in your first snipppet (define it in the range). Aside from that you'd have to use a modulo

for i in range(0,max_num):
    if(i % jump != 0):
        continue
    print(i)
Nat Gillin
  • 233
  • 2
  • 8
Sayse
  • 42,633
  • 14
  • 77
  • 146
1

start:jump:end

Example:

a = 0:10:100

You can loop using that:

for a in 0:10:100
  println(a)
end
Chris Rackauckas
  • 18,645
  • 3
  • 50
  • 81