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.

3. 2D Arrays in Java


Answer:

gradeTable[ 0 ][ 0 ]
99
gradeTable[ 1 ][ 1 ]
91
gradeTable[ 3 ][ 4 ]
93
gradeTable[ 5 ][ 2 ]
92

2D Arrays in Java

Annotation 2020-03-26 204636

In Java, a table may be implemented as a 2D array. Each cell of the array is a variable that can hold a value and works like any variable. As with one dimensional arrays, every cell in a 2D array is of the same type. The type can be a primitive type or an object reference type.

Important: Each cell of the array is specified with a row and column number, in that order.

Say that gradeTable is a 2D array of int, and that (conceptually) it looks like the table to the right. Then,

gradeTable[ 0 ][ 1 ]     // holds 42
gradeTable[ 3 ][ 4 ] // holds 93
gradeTable[ 6 ][ 2 ] // holds 78

The subscripted variables are used in assignment statements and arithmetic expressions just like any variable:

// puts a 33 into row 0 column 1. 
gradeTable[ 0 ][ 1 ] = 33 ;

// increments the value at row 3 column 4.
gradeTable[ 3 ][ 4 ]++ ;

// puts 40 into value
int value = (gradeTable[ 6 ][ 2 ] + 2) / 2 ;


Question 3:

Write a Java statement that puts a zero into row 5 column 3.