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. 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

defines module qa.controlflow.forrangewithby

  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
      stdout.println("20 ... 0 by 5:")
      for i in 20 ... 0 by 5
        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
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: step, by, increment, custom, for, range