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.
8. Using a Variable as an Index
Answer:
stuff[0] has 23
stuff[1] has 38
stuff[2] has 14
stuff[3] has 0
stuff[4] has 0
Using a Variable as an Index
int values[] = new int[7]; int index; values[ 6 ] = 42; // literal index = 0; values[ index ] = 71; // put 71 into cell 0 index = 5; values[ index ] = 23; // put 23 into cell 5 index = 3; values[ 2+2 ] = values[ index-3 ]; // same as values[ 4 ] = values[ 0 ]; |
Question 8:
Given the above declarations, is the following legal?
index = 4;
values[ index+2 ] = values[ index-1 ];