Arrays in D Programming Language

import std.stdio;

void main()
{
    // Here we create an array `a` that will hold exactly
    // 5 `int`s. The type of elements and length are both
    // part of the array's type. By default an array is
    // zero-valued, which for `int`s means `0`s.
    int[5] a;
    writeln("emp:", a);

    // We can set a value at an index using the
    // array[index] = value syntax, and get a value with
    // array[index].
    a[4] = 100;
    writeln("set:", a);
    writeln("get:", a[4]);

    // The .length property returns the length of an array.
    writeln("len:", a.length);

    // Use this syntax to declare and initialize an array
    // in one line.
    int[5] b = [1, 2, 3, 4, 5];
    writeln("dcl:", b);

    // You can also have the compiler count the number of
    // elements for you with `auto`
    auto c = [1, 2, 3, 4, 5];
    writeln("dcl:", c);

    // If you specify the index with `:`, the elements in
    // between will be zeroed.
    int[5] d = [100, 0, 0, 400, 500];
    writeln("idx:", d);

    // Array types are one-dimensional, but you can
    // compose types to build multi-dimensional data
    // structures.
    int[2][3] twoD;
    foreach (i; 0..2)
    {
        foreach (j; 0..3)
        {
            twoD[i][j] = i + j;
        }
    }
    writeln("2d: ", twoD);

    // You can create and initialize multi-dimensional
    // arrays at once too.
    int[2][3] twoD2 = [
        [1, 2, 3],
        [1, 2, 3]
    ];
    writeln("2d: ", twoD2);
}

This D code demonstrates the usage of arrays, which are similar to arrays in other languages. Here are some key points about arrays in D:

  1. Arrays in D have a fixed length that is part of their type.
  2. Array indices start at 0.
  3. Arrays are initialized with default values (0 for integers) if not explicitly initialized.
  4. You can initialize arrays with a list of values enclosed in square brackets.
  5. The .length property gives the length of an array.
  6. D supports multi-dimensional arrays.
  7. The auto keyword can be used for type inference when initializing arrays.

When you run this program, it will output:

emp:[0, 0, 0, 0, 0]
set:[0, 0, 0, 0, 100]
get:100
len:5
dcl:[1, 2, 3, 4, 5]
dcl:[1, 2, 3, 4, 5]
idx:[100, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [1, 2, 3]]

Note that arrays in D are displayed in the form [v1, v2, v3, ...] when printed, which is slightly different from some other languages.