Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Procedures and Control Flow

Loops and Ranges: for, while, break

Learn Nim loops: for over ranges and collections, countup and countdown, while, break, continue, labeled block exits, enumerate-style indexing and nested loops.

Loops repeat work. Nim has two loop statements, for and while, plus the helper iterators countup, countdown and pairs that cover almost every counting pattern. There is no C-style three-part for; instead you loop over a range or over a collection, which is shorter and removes a class of off-by-one bugs.

Nim code on this page is read-only (the compiler cannot run on this site). C stand-ins let you run the same logic.

for over ranges

NIM
for i in 1 .. 5:
  echo i              # 1 2 3 4 5   (both ends included)

for i in 0 ..< 5:
  echo i              # 0 1 2 3 4   (upper bound excluded)

.. includes the last number and ..< stops before it. For zero-based indexing use 0 ..< n, which is the form you will write most often.

To count in other ways use iterators from the system module:

NIM
for i in countup(0, 20, 5):
  echo i              # 0 5 10 15 20

for i in countdown(10, 1):
  echo i              # 10 9 8 ... 1

for i in countdown(10, 0, 2):
  echo i              # 10 8 6 4 2 0

The loop variable is a fresh constant for each iteration; you cannot assign to it. Ranges also work with characters and enums: for ch in 'a' .. 'e'.

for over collections

The same syntax walks a sequence, an array, a string or a set:

NIM
let fruits = @["apple", "banana", "cherry"]

for fruit in fruits:
  echo fruit

for ch in "nim":
  echo ch             # n i m (characters, i.e. bytes)

When you need the position too, give two variables:

NIM
for index, fruit in fruits:
  echo index, ": ", fruit      # 0: apple, 1: banana, 2: cherry

This works because the compiler calls the pairs iterator of the collection. Tables and seq all have one, so for key, value in table: works too. If you want to change items in place, loop with mitems over a var collection:

NIM
var numbers = @[1, 2, 3]
for n in mitems(numbers):
  n *= 10
echo numbers           # @[10, 20, 30]

while

NIM
var n = 1
while n < 100:
  n *= 2
echo n                 # 128

while repeats as long as the condition is true. An endless loop is while true:, normally paired with break.

break and continue

NIM
for i in 1 .. 10:
  if i mod 2 == 0:
    continue           # skip even numbers
  if i > 7:
    break              # stop the loop entirely
  echo i               # 1 3 5 7

break leaves the innermost loop, continue jumps to the next iteration.

Leaving nested loops: labeled blocks

Nim has no goto, and break only exits the innermost loop. To leave several loops at once, wrap them in a named block and break out of that:

NIM
block search:
  for row in 0 ..< 5:
    for col in 0 ..< 5:
      if row * col == 6:
        echo "found at ", row, ",", col
        break search      # leaves both loops

A block can also yield a value, which makes some searches tidy.

A loop that finds something

NIM
func firstNegative(values: seq[int]): int =
  result = 0
  for v in values:
    if v < 0:
      return v

You will learn about result and return in the procedures lesson.

Common mistakes

  • Off by one. 1 .. n has n iterations; 0 ..< n also has n. Mixing 0 .. n with indexes reads one past the end.
  • Changing the collection while iterating. Adding to or deleting from a seq inside for is checked in debug builds and raises an AssertionDefect.
  • Expecting the loop variable to be writable. It is not; copy it into a var first.
  • Forgetting var for in-place changes. mitems needs a variable collection, not a let.

Stand-in: the same loops in C

C has the classic for (init; test; step) form. This stand-in prints the same sequences as the Nim examples above, and shows a labeled exit with goto.

C Stand-in: ranges, steps and a labeled exit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: index and value together

Nim's for index, item in items is a loop with a counter. In C you write the index yourself.

C Stand-in: index/value loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which loop runs exactly 5 times with i = 0, 1, 2, 3, 4?

    ..< excludes the upper bound, so 0 ..< 5 gives five values starting at 0.
  2. 2. How do you leave two nested loops at once in Nim?

    break exits only the innermost loop; a labeled block provides the escape hatch.
  3. 3. What does for i, x in items: give you?

    The pairs iterator yields the position and the value.
  4. 4. How do you modify the elements of a seq while looping?

    mitems yields mutable references; the plain loop variable is read-only.

Summary

  • for loops over ranges (a .. b inclusive, a ..< b exclusive) and over collections; countup and countdown add steps.
  • for index, item in coll gives positions; mitems allows in-place changes.
  • while, break and continue work as in other languages; a named block lets break leave several loops.
  • Loop variables are read-only.

Next: Procedures: the basics