Sunday, September 27, 2015

Multidimensional Arrays

In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look and act like regular multidimensional arrays.

To declare a multidimensional array variable, specify each additional index using another set of square brackets.

For example, the following declares a two dimensional array variable called one.

int one[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to one. Internally this matrix is implemented as an array of arrays of int.The following program numbers each element in the array from left to right, top to bottom, and then displays these values:

// Demonstrate a two-dimensional array.
class One
{
public static void main(String args[])
{
int one[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
 
for(j=0; j<5; j++)
{
one[i][j] = k;
k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(one[i][j] + " ");
System.out.println();
}
       }
}

 This program generates the following output:

0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

No comments:

Post a Comment

If you have any query please comment here, Will get back to you :)