Iterate from 0 to 20 with a step of 5 using for-range with by.
← Control Flow · Ref: Q1149
'by' specifies the step value:
for i in 0 ... 20 by 5 stdout.println($i)
With 'by', the SIGN of the step sets the direction. To count down, use a negative step:
for i in 20 ... 0 by -5 stdout.println($i)
A positive step on a descending range (for i in 20 ... 0 by 5) runs zero times - and when the start, end and step are all written in the source the compiler refuses it (E08276), as it does a step of zero. A step that only arrives while the program runs is not reported: the loop then simply runs no iterations. Only when 'by' is left out does EK9 work out the direction from start vs end (for i in 20 ... 0 counts down by 1). See Q1148.
Example
#!ek9 defines module qa.controlflow.forrangewithby defines function wrongWayStep() <- rtn as Integer: 5 defines program ForRangeWithByDemo() stdout <- Stdout() //Step by 5 stdout.println("By 5:") for i in 0 ... 20 by 5 stdout.println($i) //Descending: with 'by', the sign of the step sets the direction stdout.println("By -5:") for i in 20 ... 0 by -5 stdout.println($i) //A positive step on a descending range runs zero times. Written in the source (by 5) the compiler //refuses it (E08276); a step that arrives while the program runs is only seen to do nothing. stdout.println("20 ... 0 by 5:") wrongWay <- wrongWayStep() for i in 20 ... 0 by wrongWay stdout.println($i) stdout.println("(no iterations)")
Common mistakes
E50001 — EK9 uses 'for i in start ... end by step'. No range() function.
Incorrect:
for i in range(0, 20, 5)
Correct:
for i in 0 ... 20 by 5
E08276 — A positive step on a descending range can never move toward the end, so the body can never run. Count down with a negative step, or leave 'by' out.
Incorrect:
for i in 20 ... 0 by 5
Correct:
for i in 20 ... 0 by -5
Other ways to ask this
- I need a loop that counts in steps of 5 instead of 1
- In Python I'd use range(0, 21, 5). Write the EK9 range with step
- Given start=0, end=20, step=5, iterate with a custom increment
- Loop through a range with a specific step value using 'by'
- How do I count down in steps with 'by' in an EK9 for-range?
Coming from another language?
Python: range(0, 21, 5). Java: for(int i=0; i<=20; i+=5). Go: for i := 0; i <= 20; i += 5. EK9: for i in 0 ... 20 by 5 (count down with a negative step: for i in 20 ... 0 by -5).
Keywords: by, custom, for, increment, range, step