Two Dimensional Arrays

This chapter expands our discussion on one-dimensional arrays to two dimensional arrays. A two dimensional array is a data structure that contains a collection of cells laid out in a two dimensional grid, similar to a table with rows and columns although the values are still stored linearly in memory. Each cell in a two dimensional array can be accessed through two indexes that specify the row number and column number respectively. Like s one dimensional array, the range of each index is from zero to the size of the row or column minus one. A nested for loop is commonly used to initialize, manipulate, and access the values in a two dimensional array.

12. Individual Rows can be Replaced


Answer:

myArray[0][0] = 1 ;
myArray[0][1] = 9 ;
myArray[0][2] = 4 ;

Individual Rows can be Replaced

replaceRowThe following answer will not work:

myArray[0] = {1, 9, 4} ;

An initializer list can only be used to initialize an array, not to assign values to it after it already exists.

Perhaps your answer was:

int[] x = {1, 9, 4} ; // declare and init x

myArray[0] = x ; // assign to myArray

This will work, but does not quite do what the question asked. The suggested answer puts the values into the required cells of the existing 1D array object of row 0.

The not-quite-right answer replaces the old row 0 with a new row. It constructs a new 1D array object that holds the desired values in its cells, then assigns that object to row 0 of myArray. The previous row 0 is now garbage.

Both answers result in myArray containing what you want. In most programs it will not matter which method you used.


Question 12:

(Thought Question: ) Can row 0 be replaced with an new 1D array that contains a different number of cells than the original row?