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:
Press + to interact
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 ...