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.

7. 2D Array Declaration


Answer:

grade 0,0: 99
grade 2,4: 96
sum: 116

2D Array Declaration

Two-dimensional arrays are objects. A variable such as gradeTable is a reference to a 2D array object. The declaration

int[][] myArray ;

says that myArray is expected to hold a reference to a 2D array of int. Without any further initialization, myArray starts out holding null. The declaration

int[][] myArray = new int[3][5] ;

says that myArray can hold a reference to a 2D array of int, creates an array object of 3 rows and 5 columns, and puts the reference in myArray. All the cells of the array are initialized to zero. The declaration

int[][] myArray = { {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0} };

does exactly the same thing as the previous declaration (and would not ordinarily be used.) The declaration

int[][] myArray = { {8,1,2,2,9}, {1,9,4,0,3}, {0,3,0,0,7} };

creates an array of 3 rows and 5 columns and initializes the cells to specific values.


Question 7:

After the last statement, what is the value myArray[1][2] ?