Two Dimensional Arrays



Two Dimensional Arrays

Just as you can imagine a one dimensional array as a single row of cells, a two dimensional array can be imagined as a grid of squares.

Here is the general syntax of declaring a 2 dimensional array:

Type[][] varname = new Type[int expr][int expr];

Here is a specific example:

int[][] table = new int[5][10];

Generally, most people refer to the first index as the row of the array and the second as the column. However, it really does not matter how you think or visualize it as long as you are consistent with your interpretation. (I will explain this later once we get to an example where we print out information from a 2D array.)

Two dimensional arrays follow all the same rules that one dimensional ones do. Now, however, the expression table[3][4] stands for a single element in the array. The expression table[3] would be a one dimensional integer array of size 10.

Once again, the most common problems with two dimensional arrays are out of bound indexes and confusing array elements with array indexes. Finally, beginning students often switch the first index with the second index, which when done randomly can cause errors.

An Example

A common use for two dimensional arrays is the implementation of board games. Imagine writing a tic-tac-toe game. You could use a two dimensional character array. Here is the start of a class that would help implement tic-tac-toe:

public class TicTacToe {

private char[][] board;

private int whoseturn;

private String[] players;

final static private char[] pieces = { 'X' , 'O' };

public TicTacToe(String player1, String player2) {

board = new char[3][3];

for (int i = 0; i 2))

return false;

return true;

}

public boolean Move(int row, int column) {

if ( (board[row][column] == '_') &&

inbounds(row,column)) {

board[row][column] = pieces[whoseturn];

return true;

}

else

return false;

}

The full implementation of this class is included in the Sample Programs.

Another example of utilizing a 2-D array is writing a Matrix class. In mathematics, matrices are objects that can be added, subtracted and multiplied, if their dimensions are appropriate for doing so. (Each matrix has a number of rows and columns, and a real number is stored in each entry.) Most applications of matrices use square matrices. Here is a small matrix class:

public class Matrix {

private double[][] m;

// values must be a square matrix

public Matrix(double[][] values) {

m = new double[values.length][values.length];

for (int i=0; i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download