How does the while loop work?

← Control Flow · Ref: Q66

EK9's while loop repeatedly executes a body as long as a Boolean condition is true. The condition is checked before each iteration, so the body may never execute if the condition is initially false.

BASIC WHILE

Loop while a condition holds:

  counter <- 0
  while counter < 5
    stdout.println($counter)
    counter: counter + 1

This prints 0, 1, 2, 3, 4. The condition 'counter < 5' is checked before each iteration.

ITERATOR PATTERN

A common use of while is consuming an iterator:

  iter <- items.iterator()
  while iter?
    stdout.println(iter.next())

The ? operator checks if the iterator is set (has more items). This continues until the iterator is exhausted.

COUNTER ACCUMULATION

Build up a result across iterations:

  sum <- 0
  n <- 1
  while n <= 100
    sum: sum + n
    n: n + 1

This computes the sum of 1 to 100.

CONDITION IS A BOOLEAN EXPRESSION

Any expression producing a Boolean works as the condition:

  while not finished and retries < maxRetries
    attempt()
    retries: retries + 1

WHILE VS FOR-RANGE

Use for-range when you know the number of iterations:

  for i in 1 ... 10

Use while when the number of iterations depends on a runtime condition:

  while hasMoreData()

WHILE VS FOR-IN

Use for-in to iterate over a collection directly:

  for item in items

Use while with an iterator when you need more control:

  while iter?

NO BREAK

There is no break statement to exit a while loop early. Use guards or restructure the condition instead. See Q144 for why break was removed and Q125 for alternatives.

While loops support guard variables (see Q74) and can return values as expressions (see Q81).

See Q61 for if statements. See Q64 for for-range loops. See Q65 for for-in loops. See Q67 for do-while loops. See Q89 for stream pipelines as loop alternatives. See Q125 for head as the only early exit mechanism. See Q287 for process-until-done patterns with while.

Example

defines module qa.flow.condition.loop

  defines function

    supplyStart() as pure
      -> initial as Integer
      <- rtn as Integer: initial

    supplyBoolean() as pure
      -> initial as Boolean
      <- rtn as Boolean: initial

  defines program

    WhileDemo()
      stdout <- Stdout()

      // === BASIC WHILE ===

      counter <- supplyStart(0)
      loopLimit <- 5
      while counter < loopLimit
        stdout.println(`Counter: ${counter}`)
        counter: counter + 1

      // === SUM ACCUMULATION ===

      sum <- 0
      n <- supplyStart(1)
      maxIterations <- 10
      while n <= maxIterations
        sum: sum + n
        n: n + 1
      stdout.println(`Sum 1..10: ${sum}`)

      // === ITERATOR PATTERN ===

      names <- ["Alice", "Bob", "Charlie"]
      iter <- names.iterator()
      stdout.println("Names via iterator:")
      while iter?
        stdout.println(`  ${iter.next()}`)

      // === COUNTDOWN ===

      remaining <- supplyStart(3)
      while remaining > 0
        stdout.println(`${remaining}...`)
        remaining: remaining - 1
      stdout.println("Done!")

      // === COMPOUND CONDITION ===

      attempts <- 0
      maxAttempts <- 5
      succeeded <- supplyBoolean(false)
      maxRetries <- 3
      while not succeeded and attempts < maxAttempts
        attempts: attempts + 1
        if attempts == maxRetries
          succeeded: true
      stdout.println(`Succeeded after ${attempts} attempts`)

Common mistakes

E07390 — EK9 has no break statement. Structure the loop condition to control termination rather than using an infinite loop with break. See ek9 -h E07390 for details.

Incorrect:

while true
        stdout.println(`Counter: ${counter}`)
        counter: counter + 1
        if counter >= loopLimit
          break

Correct:

while counter < loopLimit
        stdout.println(`Counter: ${counter}`)
        counter: counter + 1
Other ways to ask this
  • What is the while loop syntax in EK9?
  • How do I write a condition-based loop in EK9?
  • How do I loop while a condition is true in EK9?
  • How does while work in EK9?

Coming from another language?

Java: while (condition) { } with parentheses and braces required. Python: while condition: with colon and indentation, break/continue available. Rust: while condition { } with braces, loop for infinite loops, break/continue available. Go: for condition { } uses for keyword for while loops, no while keyword. C/C++: while (condition) { } with parentheses and braces. Kotlin: while (condition) { } with parentheses and braces, break/continue available. C#: while (condition) { } with parentheses and braces. JavaScript: while (condition) { } with parentheses and braces. Swift: while condition { } no parentheses, braces required. EK9: while condition with indentation, no parentheses, no braces, no break/continue, guard variables for safe assignment-and-check.

Keywords: flow, while, condition, boolean, counter, branch, loop, repeat, simple, basic, control, iterator, iterate