Saturday 8 November 2014

Multi dimensional arrays


Earlier in one dimensional array we have declared our array as int arr[] but here we declared as int arr[][]. So one thing you might be cleared now is that if you want to create n dimensional array you have to keep n [] braces after your variable name.
Next part is defining array i.e. assigning length of array. Here we defined our array as new int[10][10]. It says that our array contains 10 rows each row containing 10 columns. If you don't get the idea just draw a table with 10 rows and 10 columns and that is your arr[10][10].

As you can expect here now our array can contain 10*10=100 integer variable.
How to access 2D-Array
A 2D-Array can be accessed by specifying row and column
Ex: arr[1][2] specifies 2nd row 3rd column. In general arr[i][j]  means i+1th row j+1th column.
We can assign values to our array by simple assignment operation.
Ex: arr[1][2]=10; In the same we can print the variable by accessing row and column.
Class test{
        public static void main(String args[]){
                   int arr[]=new int[10][10];
                   arr[1][2]=15;
                   arr[2][1]=10;
                   arr[5][5]=arr[1][2]+arr[2][1];
                    System.out.println(arr[5][5]);
          }
}
Find out output, by interpreting line by line.
Output will be 25. Understand how it comes.

No comments:

Post a Comment