Arrays

This chapter introduces arrays, a common multi-dimensional data structure used to store data of the same type. (Note that a class is a "data type" in this sense.) Arrays have some number of dimensions and a number of elements in each dimension. These are established when the array is created. The range of the array's index in each dimension goes from zero to the number of that dimension's elements minus one. A for loop is commonly used to initialize, manipulate, and access the values in an array. Here, we treat one-dimensional arrays, sometimes called vectors.

11. Initializer Lists


Answer:

    val[3] == 25.5

Initializer Lists

You can declare, construct, and initialize the array all in one statement:

int[] data = {23, 38, 14, -3, 0, 14, 9, 103, 0, -56 };

This declares reference variable data for an array of int. Then it constructs an int array of 10 cells (indexed 0..9) with the designated values into the cells. The first value in the initializer list corresponds to index 0, the second value corresponds to index 1, and so on. (So in this example, data[0] gets the 23.) Finally it puts a reference to the array object in the variable data .

You do not have to say how many cells the array has. The compiler will count the values in the initializer list and make that many cells. Once an array has been constructed, the number of cells does not change. Initializer lists are usually used only for small arrays.

The initializer has to be part of the declaration, as above. The following does not work.

int[] data;

// error
data = {23, 38, 14, -3, 0, 14, 9, 103, 0, -56 };

Question 11:

Write a declaration for an array of double named dvals that is initialized to contain 0.0, 0.5, 1.5, 2.0, and 2.5.