Loops

D provides four loop constructs.

1) while

while loops execute the given code block while a certain condition is met:

while (condition) {
    foo();
}

2) do ... while

The do .. while loops execute the given code block while a certain condition is met, but in contrast to while the loop block is executed before the loop condition is evaluated for the first time.

do {
    foo();
} while (condition);

3) Classical for loop

The classical for loop known from C/C++ or Java with initializer, loop condition and loop statement:

for (int i = 0; i < arr.length; i++) {
    ...

4) foreach

The foreach loop which will be introduced in more detail in the next section:

foreach (el; arr) {
    ...
}

Special keywords and labels

The special keyword break will immediately abort the current loop. In a nested loop a label can be used to break out of any outer loop:

outer: for (int i = 0; i < 10; ++i) {
    for (int j = 0; j < 5; ++j) {
        ...
        break outer;

The keyword continue starts with the next loop iteration.

In-depth

rdmd playground.d

{{programOutput}}