For in D Programming Language

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

import std.stdio;

void main() {
    // The most basic type, with a single condition.
    int i = 1;
    while (i <= 3) {
        writeln(i);
        i = i + 1;
    }

    // A classic initial/condition/after for loop.
    for (int j = 0; j < 3; j++) {
        writeln(j);
    }

    // Another way of accomplishing the basic "do this
    // N times" iteration is to use a foreach loop with iota.
    import std.range : iota;
    foreach (i; 0 .. 3) {
        writeln("range ", i);
    }

    // A loop without a condition will run repeatedly
    // until you break out of the loop or return from
    // the enclosing function.
    while (true) {
        writeln("loop");
        break;
    }

    // You can also continue to the next iteration of
    // the loop.
    foreach (n; 0 .. 6) {
        if (n % 2 == 0) {
            continue;
        }
        writeln(n);
    }
}

When you run this program, you’ll see:

$ rdmd for.d
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

D provides several looping constructs, including while, do-while, for, and foreach. The foreach loop is particularly useful for iterating over ranges and arrays.

We’ll see some other loop forms later when we look at ranges, arrays, and other data structures.