Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Control Flow and Functions

Loops in D: for, while, do-while and foreach

Repeat work in D with for, while, do-while and the powerful foreach over ranges, arrays and associative arrays, plus break, continue, labels and foreach_reverse.

Loops repeat code. D has the four classic forms, but day to day you will write foreach more than all the others together: it walks arrays, ranges and hash maps without index arithmetic, so entire categories of off-by-one errors never appear. This lesson covers each loop, the loop-control statements, labels for nested loops, and foreach_reverse. D code is read-only; C stand-ins show the underlying loop mechanics.

while and do-while

D
import std.stdio;

void main()
{
    int n = 3;
    while (n > 0)
    {
        writeln("countdown ", n);
        --n;
    }

    int tries = 0;
    do
    {
        ++tries;
    } while (tries < 3);
    writeln("tries: ", tries);    // tries: 3
}

while tests before each pass, so it may run zero times. do ... while tests after, so it always runs at least once. Note the semicolon after the do-while condition.

for

for (init; condition; step) is the C loop. Use it when you need unusual stepping:

D
for (int i = 10; i > 0; i -= 3)
{
    write(i, " ");     // 10 7 4 1
}
writeln();

Any of the three parts can be empty, and for (;;) loops forever until a break.

foreach

foreach iterates over anything iterable and gives the compiler the work of managing the index:

D
import std.stdio;

void main()
{
    int[] nums = [10, 20, 30];

    foreach (n; nums)               // values
    {
        write(n, " ");              // 10 20 30
    }
    writeln();

    foreach (i, n; nums)            // index and value
    {
        writefln("nums[%d] = %d", i, n);
    }

    foreach (i; 0 .. 5)             // a range of numbers, 5 excluded
    {
        write(i, " ");              // 0 1 2 3 4
    }
    writeln();

    string[string] capital = ["France": "Paris", "Japan": "Tokyo"];
    foreach (country, city; capital)     // key and value
    {
        writeln(country, ": ", city);
    }

    foreach_reverse (n; nums)       // backwards
    {
        write(n, " ");              // 30 20 10
    }
    writeln();
}

Important details:

  • The loop variable is a copy by default. To modify the elements, declare it with ref: foreach (ref n; nums) n *= 2;.
  • The element type is inferred. For strings it decodes code points automatically (see Characters and strings).
  • Associative array order is unspecified; do not rely on it. Sort the keys when output order matters.
  • A foreach over a range such as 0 .. n is as fast as a C for loop.
  • You must not add or remove elements of the array you are iterating over, or the loop may skip or repeat items.

break, continue and labels

break leaves the innermost loop (or switch); continue jumps to the next iteration. A label lets you act on an outer loop:

D
outer:
foreach (row; 0 .. 4)
{
    foreach (col; 0 .. 4)
    {
        if (col == 2) continue;          // next col
        if (row == 2) break outer;       // leave both loops
        writef("(%d,%d) ", row, col);
    }
}
writeln();
// (0,0) (0,1) (0,3) (1,0) (1,1) (1,3)

goto exists, but labelled break/continue cover nearly all real needs without it.

Which loop?

foreach Walk arrays, ranges, maps
for Custom start, stop and step
while Repeat until a condition fails
do-while Always run at least once

Default to foreach

1 / 2

C stand-ins for the loop forms

C has no foreach, so the stand-in shows the pattern a foreach hides: an index, a bound and an element read.

C C stand-in: what foreach does for you

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.

You will see the three indexed lines, then 30 20 10, then 10 7 4 1. The reverse loop uses i-- > 0 to avoid an unsigned underflow, a subtlety foreach_reverse removes.

C C stand-in: labelled break and continue with goto

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.

The output is (0,0) (0,1) (0,3) (1,0) (1,1) (1,3), the same as the D version. C needs goto for what D calls break outer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many times does foreach (i; 0 .. 5) run?

    The range is half-open: 0, 1, 2, 3, 4.
  2. 2. How do you modify array elements inside foreach?

    By default the loop variable is a copy; ref makes it an alias.
  3. 3. What does break outer; do?

    A labelled break leaves the named loop.
  4. 4. Which loop always runs its body at least once?

    do-while tests its condition after the body.

Summary

  • Prefer foreach for arrays, ranges and associative arrays; add ref to modify elements.
  • 0 .. n is a half-open range; foreach_reverse walks backwards.
  • Use for for unusual steps, while and do-while for condition-driven loops.
  • Labelled break and continue handle nested loops without goto.

Next: Functions