For in Nim

Nim provides several ways to create loops. Here are some basic types of loops in Nim.

import strformat

# The most basic type, with a single condition.
var i = 1
while i <= 3:
  echo i
  i = i + 1

# A classic initial/condition/after loop.
for j in 0..<3:
  echo j

# Another way of accomplishing the basic "do this N times" iteration.
for i in 0..<3:
  echo fmt"range {i}"

# A loop without a condition will repeat indefinitely
# until you `break` out of it or `return` from the enclosing function.
while true:
  echo "loop"
  break

# You can also `continue` to the next iteration of the loop.
for n in 0..<6:
  if n mod 2 == 0:
    continue
  echo n

When you run this program, you’ll see:

$ nim c -r for.nim
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Nim, the for loop is typically used with ranges or iterables. The while loop is used for condition-based looping. The break and continue statements work similarly to other languages.

Nim also provides other loop constructs and iterators that we’ll see later when we look at sequences, tables, and other data structures.