Array Initialization and Basic Array Operations
This lesson explains how arrays can be initialized and the basic operations that can be performed on elements of an array.
Initializing the elements #
Like every variable in D, the elements of arrays are automatically initialized. The initial value of the elements depends on the type of the elements: 0 for int
, double.nan for double
, etc.
All of the elements of the values array above are initialized to double.nan:
double[5] values; // elements are all double.nan
Obviously, the values of the elements can be changed later during the execution of the program. We have already seen that in the previous lesson when assigning to an element of an array:
monthDays[11] = 31;
That also happened when reading a value from the input:
readf(" %s", &values[counter]);
Sometimes the desired values of the elements are known at the time the array is defined. In such cases, the initial values of the elements can be specified on the right-hand side of the assignment operator within square brackets. Let’s see this in a program that reads the number of the month from the user and prints the number of days in that month:
Get hands-on with 1400+ tech skills courses.