Friday 7 February 2014

Multi Dimensional Arrays

Multidimensional arrays are actually arrays of arrays.

   Syntax to create two dimensional Array
      dataType arrayName[][] = new dataType[size1][size2]
         (OR)
      dataType[][] arrayName;

      arrayName = new dataType[size1][size2]

   for Example consider the array of size 5*4.
      int arr[][] = new int[5][4];

00 01 02 03
10 11 12 13
20 21 22 23
30 31 32 33
40 41 42 42

Table 1 : Array indexes
100 553 512 -9
12 32 43 56
1 3 5 7
9 -87 -98 0
-12 46 78 97

Table 2 : Values stored in Array
When you compare table1 and table 2

arr[0][0] = 100
arr[0][1] = 553
arr[0][2] = 512
arr[0][3] = -9

Example
class ArrayEx{ 
 public static void main(String args[]){
  int arr[][] = new int[5][4];

  arr[0][0] = 100;
  arr[0][1] = 553;
  arr[0][2] = 512; 
  arr[0][3] = -9;

  arr[1][0] = 12; 
  arr[1][1] = 32;
  arr[1][2] = 43; 
  arr[1][3] = 56;

  arr[2][0] = 1; 
  arr[2][1] = 3;
  arr[2][2] = 5; 
  arr[2][3] = 7;

  arr[3][0] = 9; 
  arr[3][1] = -87;
  arr[3][2] = -98; 
  arr[3][3] = 0;

  arr[4][0] = -12; 
  arr[4][1] = 46;
  arr[4][2] = 78; 
  arr[4][3] = 97;

  /*Display Elements */
  for(int i=0; i<5; i++){
   for(int j=0; j<4; j++){
    System.out.print(arr[i][j] +"\t");
   }
   System.out.println();
  }
 } 
}

Output
100 553 512 -9
12 32 43 56
1 3 5 7
9 -87 -98 0
-12 46 78 97
      

One Dimensional Array                                                 Jagged Arrays                                                 Home

No comments:

Post a Comment