Arrays
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.