Listen to this article

We have already seen Arrays in an earlier post…to recap, an array is used to store homogenous elements at fixed locations. Two dimensional arrays are used to store elements in row and column format as in a matrix.

Column 1Column 2
Row 11 (element at 0,0)4(element at 0,1)
Row 26 (element at 1,0) 5 (element at 1,1)

We can the see 2X2 matrix above. That is – the table above consists of 2 rows and 2 columns and stores only integers. A 2X2 matrix will have 4 elements and similarly a 3X3 matrix will have 9 elements and so on.

If we call our integer 2D array as ‘g[][]’, this is one way we can declare it:

int[][] g={{1,4}, {6,5}};

How do we represent this by means of Java program? We make use of nested loops.

 

In the above example, we make use of two ‘for’ loops. We get the input from the user by means of the Scanner class and then assign it to the appropriate place in the matrix. The results are then printed out. This is a very simple example when working with two dimensional arrays.

This same example can be extended to multi-dimensional arrays(like 3X3, 4X4 and more) We can perform different operations on multi-dimensional arrays like addition, subtraction, printing only certain elements and more. Multi-dimensional arrays can also be used to store other data types such float, String and more.

Come back tomorrow for more ! 🙂

I’m participating in #BlogchatterA2Z by Blogchatter 

(Visited 43 times, 1 visits today)

Related Posts

3 thoughts on “Two dimensional arrays

Leave a Reply