|
The array elements are selected using a one index
Example:
|
In a rectangular 2-dimensional arrays, each row and column in the array has the same number of array elements.
Example:
|
Example:
|
(We will only discuss and use rectanglar 2-dimensional arrays in this course).
|
|
Example:
public class TwoDimArray1
{
public static void main(String[] args)
{
double[][] a = {
{ 1.0, 2.0, 3.0, 4.0 }, // *** Defining an
{ 2.0, 5.0, 1.0, 7.0 }, // *** initialized
{ 4.0, 1.0, 2.0, 8.0 } // *** 2-dim. array
};
******************************************
Ignore the rest of the program for now...
******************************************
int i, j; // Array indices
/* ----------------- Print 2-dim array a -------------------- */
// Print elements in row i
for ( i = 0 ; i < a.length ; i++ )
{
// Print column j in row i
for ( j = 0 ; j < a[i].length ; j++ )
{
System.out.print( a[i][j] + " " );
}
System.out.println();
}
}
}
|
|
ArrayRefVariable [ index1 ] [ index2 ]
|
Example: (assuming that a is a reference variable to a 2-dimensional array)
|
m = # rows
n = # columns
|
Then we can use the following nest for-loop to visit all elements:
for ( int i = 0; i < m; i++ )
{
// variable i runs through all rows in the array
for ( int j = 0; j < n; j++ )
{
Use array element a[i][j] // Visit a[i][j]
}
}
|
This is discussed next.
(Code segment)
double[] a;
a = new double[ anyVlaue ];
for ( i = 0; i < a.length; i++ )
{
visit (= use) array element a[i]
}
|
|
Pseudo code:
for ( each row index i = 0, 1, 2, .... a.length )
{
visit (= use) all array elements in row i
}
|
Note:
|
|
|
We can now refine the psuedo code to visit all elements in a 2-dimensional array:
for ( each row index i = 0, 1, 2, .... a.length )
{
visit (= use) all array elements in row i
}
|
Refined pseudo code:
for ( each row index i = 0, 1, 2, .... a.length )
{
for ( each column index j = 0, 1, 2, ...., a[i].length )
{
visit (= use) a[i][j]
}
}
|
public class TwoDimArray1
{
public static void main(String[] args)
{
double[][] a = {
{ 1.0, 2.0, 3.0, 4.0 },
{ 2.0, 5.0, 1.0, 7.0 },
{ 4.0, 1.0, 2.0, 8.0 }
};
int i, j; // Array indices
/* ----------------- Print 2-dim array a -------------------- */
// Print elemenst in row i
for ( i = 0 ; i < a.length ; i++ )
{
// Print element j in row i
for ( j = 0 ; j < a[i].length ; j++ )
{
System.out.print( a[i][j] + " " );
}
System.out.println();
}
}
}
|
How to run the program:
|