Two Dimensional Arrays
Site: | Saylor Academy |
Course: | CS101: Introduction to Computer Science I |
Book: | Two Dimensional Arrays |
Printed by: | Guest user |
Date: | Wednesday, October 30, 2024, 3:29 PM |
Description
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.
Table of contents
- 1. Two Dimensional Arrays
- 2. Table of Student Grades
- 3. 2D Arrays in Java
- 4. Headings are not part of the Array
- 5. Bounds Checking
- 6. 2D Array of int
- 7. 2D Array Declaration
- 8. Different Numbers of Cells per Row
- 9. Length of a 2D Array
- 10. Length of each Row
- 11. Implementation of 2D Array
- 12. Individual Rows can be Replaced
- 13. Usual View of a 2D Array
- 14. Printing a 2D Array
- 15. Null Rows
- 16. End of the Chapter
1. Two Dimensional Arrays
Often data comes naturally in two dimensional form. Web browser screens are two dimensional, as are spreadsheets, printed pages, and images.
For many of these situations you need a two-dimensional array. This is a collection of cells laid out in a 2D grid, like graph paper. Each cell can hold a value (as with a 1D array). However, now two indexes are needed to specify a cell.
If you have ever used a spreadsheet then you have used a 2D grid for holding and manipulating data.
One programming problem in the 2014 Advanced Placement test for computer science required use of a two dimensional array of object references.
Chapter Topics:
- Two-dimensional Arrays
- 2D Array Declaration
- Initializer Lists
- Different Numbers of cells in each row
- 2D Arrays as Arrays of 1D Arrays
- Printing a 2D Array
Question 1:
(Thought question: ) Do you suspect that 2D arrays in Java are objects?
Source: Bradley Kjell, http://programmedlessons.org/Java9/chap67/ch67_01.html
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.
2. Table of Student Grades
Answer:
Yes
Table of Student Grades
Imagine a class of 7 students that have a quiz every week for 5 weeks. The instructor records the grades in a table. A particular cell of the table is designated by student number and week number. For example:
- The grade for student 0 week 1 is 42
- The grade for student 3 week 4 is 93
- The grade for student 6 week 2 is 78
To specifying a cell use row and column indexes like this:
gradeTable[ row ][ col ]
As with one dimensional arrays, indices start at zero. For example:
- gradeTable[ 0 ][ 1 ] is 42
- gradeTable[ 3 ][ 4 ] is 93
- gradeTable[ 6 ][ 2 ] is 78
Question 2:
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
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:
4. Headings are not part of the Array
Answer:
gradeTable[ 5 ][ 3 ] = 0;
Headings are not part of the Array
The row and column numbers are not part of the array. They are usually shown in pictures of an array, but the array object does not explicitly contain the indexes. When you ask for
gradeTable[ 5 ][ 3 ]
Java knows what cell you mean and goes there directly.
More Important Stuff:
- Rows are numbered from 0 to N-1, where N is the number of rows
- Columns are numbered from 0 to M-1, where M is the number of columns.
- A 2D array with N rows and M columns per row will have N times M number of cells.
- However, it is possible for a 2D array to have a different number of cells in each row.
Details about these issues will follow.
Question 4:
5. Bounds Checking
Answer:
No. The indicated array element (cell) does not exist.
Bounds Checking
When your program is running and it tries to access an element of an array, the Java virtual machine checks that the array element actually exists. This is called bounds checking. If your program tries to access an array element that does not exist, the Java virtual machine will generate an:
ArrayIndexOutOfBoundsException
Ordinarily, this will halt your program. Of course, as with 1D arrays, array indexes must be an integer type.
It makes no sense to access gradeTable[ 3.5 ][ 2 ]
.
As with a 1D array, an array index may be an integer literal, a variable of integer type, a method that evaluates to an integer, or an arithmetic expression involving all of these things:
- gradeTable[ 3 ][ j ] = 34;
- sum = gradeTable[ i ][ j ] + gradeTable[ i ][ j+1 ] ;
- value = gradeTable[ 2 ][ someFunction() ] ;
- gradeTable[ 1 ][ 0 ] = gradeTable[ i+3 ][ someFunction()-2 ] ;
We are not likely to need a statement as complicated as the last one.
Question 5:
(Review: ) must the elements of a 2D array be all of the same type?
6. 2D Array of int
Answer:
Yes, just as for 1D arrays.
If you want a collection of a variety of types, you probably want to define your own class to contain them.
2D Array of int
int
The following program creates a 2D array of int
that implements the gradeTable
example. Details about declaring and constructing 2D arrays will be explained later.
The declaration of gradeTable
uses an initializer list as a short-cut way to create a 2D array object and place values into it. The list contains 7 rows each separated by a comma; each row is a list of
values.
class gradeExample { public static void main( String[] arg ) { // declare and construct a 2D array int[][] gradeTable = { {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87, 94}, {43, 98, 78, 56, 99} }; System.out.println("grade 0,0: " + gradeTable[0][0]); System.out.println("grade 2,4: " + gradeTable[2][4]); gradeTable[5][3] = 99 ; int sum = gradeTable[0][1] + gradeTable[0][2] ; System.out.println( "sum: " + sum ); } } |
Question 6:
What does the program print out?
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]
?
8. Different Numbers of Cells per Row
Answer:
What is the value myArray[1][2]
? 4
(Remember that array indexes start at 0 for both rows and columns.)
Different Numbers of Cells per Row
class UnevenExample { public static void main( String[] arg ) { // declare and construct a 2D array // int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; System.out.println("uneven[0][2] is ", + uneven[0][2] ) ; // OK System.out.println("uneven[1][1] is ", + uneven[1][1] ) ; // OK System.out.println("uneven[1][2] is ", + uneven[1][2] ) ; // WRONG! uneven[2][4] = 97; // OK uneven[1][4] = 97; // WRONG! int val = uneven[0][2] ; // OK int sum = uneven[1][2] ; // WRONG! } } |
Each row of a 2D array may have a different number of cells. In the example, the array uneven
has
- 3 cells in its first row,
- 2 in its second row,
- and 5 in its last row.
If a program refers to a cell that does not exist, bounds checking will catch the error (as the program runs) and generate an exception (which usually will halt your program.)
Notice that row 1 in the above has only two cells. (It is incorrect to think that row 1 has more cells but that only the first two are initialized.) Making an assignment to a cell that does not exist is an error.
Question 8:
9. Length of a 2D Array
Answer:
int[][] uneven =
{ { 1, 9, 4 },
{ 0, 2},
{ 0, 1, 2, 3, 4 } };
Which of the following exist?
- uneven[ 0 ][ 2 ] OK
- uneven[ 1 ][ 1 ] OK
- uneven[ 2 ][ 5 ] WRONG
- uneven[ 3 ][ 0 ] WRONG
Length of a 2D Array
class UnevenExample2 { public static void main( String[] arg ) { // declare and construct a 2D array int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; System.out.println("Length is: " + uneven.length ); } } |
Question 9:
10. Length of each Row
Answer:
Length is: 3
Length of each Row
The length of a 2D array is the number of rows it has. The row index runs from 0 to length-1.
Each row of a 2D array can have a different number of cells, so each row has its own length
:
uneven[0]
refers to row 0 of the array, uneven[1]
refers to row 1, and so on.
class unevenExample3 { public static void main( String[] arg ) { // declare and construct a 2D array int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; // length of the array (number of rows) System.out.println("Length of array is: " + uneven.length ); // length of each row (number of its columns) System.out.println("Length of row[0] is: " + uneven[0].length ); System.out.println("Length of row[1] is: " + uneven[1].length ); System.out.println("Length of row[2] is: " + uneven[2].length ); } } |
Question 10:
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:
12. Individual Rows can be Replaced
Answer:
myArray[0][0] = 1 ; myArray[0][1] = 9 ; myArray[0][2] = 4 ;
Individual Rows can be Replaced
The 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:
13. Usual View of a 2D Array
Answer:
Yes
Usual View of a 2D Array
Usually you think of a 2D array as a table, not the complicated structure of the previous page. For example,
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
is usually thought of as like the table on the right. Only occasionally do you have to think of "arrays of references to 1D arrays."
Now consider how you would print out every element contained in array uneven
.
Question 13:
14. Printing a 2D Array
Answer:
- How many rows must be printed?
- 3
- How many cells in each row must be printed?
- 3 for row 0
- 2 for row 1
- 5 for row 3
Printing a 2D Array
Here is a program that creates a 2D array, then prints it out.
The nested loops are written to print out the correct number of cells for each row. The expression uneven[row].length evaluates to a different integer for each row of the array.
|
Question 14:
For the print method to work, must every row of uneven
be non-null
?
15. Null Rows
Answer:
Yes. If a row does not exists (and therefore
uneven[row]
isnull
) the following code will throw anException
:for ( int col=0; col < uneven[row].length; col++ )
Null Rows
length
is used:
|
However, the code does assume that
uneven
is non-null
.Question 15:
(Thought Question: ) Are 3-dimensional arrays possible?
16. End of the Chapter
Answer:
Yes. But lets skip that for now. 2D arrays are usually as high as you need to go. 3D arrays get very big. A 3D array of 100
sheets of 2D arrays, where each 2D array has 100 rows and 100 columns would have 100*100*100 cells, 1,000,000 cells.
That is an awful lot of data. Usually some other type of data structure would be used.
End of the Chapter
You have reached the end this chapter. You may wish to review the following. Click on a subject that interests you to go to where it was discussed.
- array, two dimensional Two-dimensional array.
- array, row and column numbers Row and column numbering.
- bounds checking Bounds checking.
- array declaration, 2D Array declaration.
- array, 2D uneven rows Differing numbers of cells per row.
- array, length Length of a 2D array.
- array, row length Length of each row.
- array, implementation Implementation of a 2D array.
- array, 2D printing Printing a 2D array.