Arrays

In this lesson, we will discuss arrays, how arrays are declared and how data is accessed in an array.

If we need five different values to perform some calculations, we will have to store those values in five different variables. The declaration of those five variables will look like this:

double value_1;
double value_2;
double value_3;
double value_4;
double value_5;

This method of defining variables individually does not scale to cases where even more variables are needed. Imagine needing a thousand values; it is almost impossible to define a thousand variables from value_1 to value_1000.

Arrays are useful in such cases: the array feature allows us to define a single variable that stores multiple values of the same type together. Although simple, arrays are the most commonly used data structures to store a collection of values.
This chapter covers only some of the features of arrays. More features will be introduced later in the slices and other array features lesson.

Definition #

Array definition in D
Array definition in D

The definition of array variables is very similar to the definition of normal variables. The only difference is that the number of values associated with the variable is specified in square brackets. We can contrast the two definitions as follows:

int singleValue;
int[10] arrayOfTenValues;

The first line above is the definition of a variable that stores a single value, just like the variables that we have defined so far. The second line is the definition of a variable that stores ten consecutive values. In other words, it stores an array of ten integer values. You can also think of it as defining ten variables of the same type. ...