foreach Loop
This lesson explains the foreach loop and how it is used with different data structures in D.
What is the foreach
loop? #
One of the most commonly used statements in D is the foreach
loop. It is used to perform the same operation to every element of a container (or a range).
Operations that are applied to elements of containers are very common in programming. We have seen in the for loop lesson that the elements of an array are accessed with an index value that is incremented at each iteration:
import std.stdio;void main() {int [] array = [1, 2, 3, 4, 5];for (int i = 0; i < array.length; ++i) {writeln(array[i]);}}
The following steps are involved in iterating over all the elements:
-
Defining a variable as a counter, which is conventionally named as
i
-
Iterating the loop up to the value of the
.length
property of the array -
Incrementing
i
-
Accessing the element
foreach
has essentially the same behavior, but it simplifies the code by handling those steps automatically:
foreach (element; array) {
writeln(element);
}
Part of the power of foreach
comes from the fact that it can be used the same way regardless of the type of the container. As we have already seen, one way of iterating over the values of an associative array ...