A Beginner's Guide to D/Conditions and Loops/Simple Iteration

From Wikibooks, open books for an open world
Jump to: navigation, search


Simple Iteration: The foreach loop[edit]

The foreach statement provides a number of ways to iterate through an array in either direction. It takes as its arguments the name of a variable that will contain an element in the array, and the array to be traversed. It is followed by the statements to be executed. It is possible to obtain the index used to find a specific position in the array. In the following example we initialize an array of integers and iterate through it using foreach and foreach_reverse. You do not need to specify a type for the value.

import std.stdio;
 
int main()
{
    int[] arr = [ 1, 3, 5 ];
 
    foreach (value; arr)
        writefln("foreach: value = %d", value);
 
    foreach (index, value; arr)
    {
        writefln("foreach: index = %d, value = %d", index, value);
    }
 
    foreach_reverse (index, value; arr)
    {
        writefln("foreach_reverse: index = %d, value = %d", index, value);
    }
 
    return 0;
}

As with the if statement in previous chapters, you do not need brackets if there is only one statement following foreach. It is worth noting the use of a comma instead of semi-colon between index and value.

The code prints out the following:

foreach: value = 1
foreach: value = 3
foreach: value = 5
foreach: index = 0, value = 1
foreach: index = 1, value = 3
foreach: index = 2, value = 5
foreach_reverse: index = 2, value = 5
foreach_reverse: index = 1, value = 3
foreach_reverse: index = 0, value = 1

Cycling using foreach is done on a copy of the values, meaning that changes to them are not reflected in the originals. If we want to change the original array's values, that can be done by adding the type modifiers out or ref (equal to inout). The first can only be written to, the second can be read and written. If you attempt to read an out variable, it will be initialized. Adding the type modifier to an array index results in a compiler error.

  int[] arr = [ 1, 3, 5 ];
 
  foreach (ref value; arr)
  {
      value++;
  }
 
  foreach (key, inout value; arr)
  {
      value += 10; // Adds 10 to value
  }
 
  foreach (key, value; arr)
  {
      writefln("arr[%d] = %d", key, value);
  }

Output:

arr[0] = 12
arr[1] = 14
arr[2] = 16