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.
11. Implementation of 2D Array
Answer:
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
- Length of array is: 3
- Length of row[0] is: 3
- Length of row[1] is: 2
- Length of row[2] is: 5
Implementation of 2D Array
A two dimensional array is implemented as an array of one dimensional arrays. This is not as awful as you might think. It is an extension of what you already know about one dimensional arrays of objects. The declaration
int[][] myArray; // 1.
declares a variable myArray
which in the future may refer to an array object. At this point, nothing has been said about the number of rows or columns.
To create an array of 3 rows do this:
myArray = new int[3][] ; // 2.
Now myArray
refers to an array object. The array object has 3 cells. Each cell may refer (in the future) to an array of int
, an int[]
object. However none of the cells yet refer to an object. They are initialized to null.
One way to create row 0 is this:
myArray[0] = new int[3] ; // 3.
This creates a 1D array object and puts its reference in cell 0 of myArray
. The cells of the 1D array are initialized to 0.
A previously constructed 1D array can be assigned to a row:
int[] x = {0, 2};
int[] y = {0, 1, 2, 3, 4} ;
myArray[1] = x ;
myArray[2] = y ; // 4.
The rows do not need to have the same number of cells.
The preceding statements construct the 2D array step-by-step. Usually you would not do this.
Question 11: