You can also declare arrays that are 2 dimensional. These arrays have two subscripts, one for the row and one for the column. This is the declaration of a 2-D array and a picture of its representation in memory.
int twodim [4][4];
2-D arrays are not the same as arrays of records. Arrays of records only have one dimension. The individual elements of the array just contain more than one piece. In 2-D arrays each element has only one thing and they are all of the same type.
Here is an example of a 2-D array. It stores a X-O game and shows how you manipulate a 2-D array.
public class twodimensional
{
public static void main (String args [])
{
int twoD [] [] = new int [3] [4];
initialize (twoD, 3, 4);
printarray (twoD, 3, 4);
char XandO [] [] = new char [3] [3];
initialize (XandO, 3, 3);
XandO [0] [0] = 'X';
XandO [0] [1] = 'O';
XandO [2] [2] = 'X';
printarray (XandO, 3, 3);
}
public static void initialize (char twoD [] [], int sizex, int sizey)
//Pre: twoD is an array of size row and col
//Post: twoD has values (any values)
{
for (int i = 0 ; i < sizex ; i++)
{
for (int j = 0 ; j < sizey ; j++)
{
twoD [i] [j] = '-';
}
}
}
public static void printarray (char twoD [] [], int sizex, int sizey)
//Pre: twoD is an array of size row and col
//Post: twoD is printed on the screen
{
for (int i = 0 ; i < sizex ; i++)
{
for (int j = 0 ; j < sizey ; j++)
{
System.out.print (twoD [i] [j]);
}
System.out.println ();
}
}
}
Output:
X O -
- - -
- - X
if you make a change to the array in a function, the array will stay changed outside the function.
you should always remember to pass the size of the array to the function. For example:
Note that when you call the function, you do not need to type array[ ]. The computer knows that it is an array because you declared it as an array.