Two Dimensional Arrays

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

With 2D arrays remember: