161,191 views
12 votes
12 votes
Explain two dimensional arrays an example ​

User Kevin Verstraete
by
3.0k points

1 Answer

15 votes
15 votes

TWO-DIMENSIONAL ARRAYS were introduced in Subsection 3.8.5, but we haven't done much with them since then. A 2D array has a type such as int[][] or String[][], with two pairs of square brackets. The elements of a 2D array are arranged in rows and columns, and the new operator for 2D arrays specifies both the number of rows and the number of columns. For example,

int[][] A;

A = new int[3][4];

This creates a 2D array of int that has 12 elements arranged in 3 rows and 4 columns. Although I haven't mentioned it, there are initializers for 2D arrays. For example, this statement creates the 3-by-4 array that is shown in the picture below:

int[][] A = { { 1, 0, 12, -1 },

{ 7, -3, 2, 5 },

{ -5, -2, 2, -9 }

};

An array initializer for a 2D array contains the rows of A, separated by commas and enclosed between braces. Each row, in turn, is a list of values separated by commas and enclosed between braces. There are also 2D array literals with a similar syntax that can be used anywhere, not just in declarations. For example,

A = new int[][] { { 1, 0, 12, -1 },

{ 7, -3, 2, 5 },

{ -5, -2, 2, -9 }

};

All of this extends naturally to three-dimensional, four-dimensional, and even higher-dimensional arrays, but they are not used very often in practice.

User Ikechukwu
by
3.2k points