Write about Two dimensional array in Java?
https://www.computersprofessor.com/2017/01/write-about-two-dimensional-array-in.html
Two dimensional array:
|
There will be
situations where a table of values will have to be stored.
Java allows us
to define such tables of items by using two dimensional arrays.
Eg; V[4][3];
Two dimensional arrays are stored an
memory as follows:
As with the single dimensional arrays, each dimension of the array is indexed from zero to its maximum size minus one, the first index selects the row and the second index selects the column within that row.
For using
two–dimensional arrays, we must follow the same steps as that of simple
arrays. We may create a two–dimensional array like this:
int myArray [
] [ ];
myarray=new
int[3][4];
(or)
int myArray [
] [ ]=new int [3][4];
This creates a
tables that can store 12 integer values, four across and three down.
Like the
one–dimensional arrays, two dimensional arrays may be initialized by following
their declaration with a list of initial values enclosed in braces. For
example
int table
[2][3]={0, 0, 0, 1, 1, 1};
initializes
the elements of the first row to zero and the second row to one. The
initialization is done row by row. The above statements can be equivalently
written as
int table [ ]
[ ]={{0, 0, 0}, {1, 1, 1}};
by surrounding
the elements of each row by braces. We can also initialize a two dimensional
array in the form of a matrix as shown
below.
int table [ ]
[ ]={
{0, 0, 0},
{1, 1, 1}
};
We can type to
a value stored in a two–dimensional array by using subscripts for both the
column and row of the corresponding element. Example
int
value=table[1][2];
the retrieves
the value stored in the second row and third column of table matrix
a quick way to
initialize a two–dimensional array is to use nested for loops as shown below:
for(i=0;
i < 5; i ++)
|
{
for(j=0; j < 5; j ++)
{
if(i==j)
table[i][j]=1;
else
table
[i][j]=0;
}
}
This will set
all the diagonal elements to 1 and others to zero an given below.
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1