Java Reference
In-Depth Information
C
HAPTER
S
UMMARY
1.
A two-dimensional array can be used to store a table.
2.
A variable for two-dimensional arrays can be declared using the syntax:
elementType[][] arrayVar
.
3.
A two-dimensional array can be created using the syntax:
new elementType
[ROW_SIZE][COLUMN_SIZE]
.
4.
Each element in a two-dimensional array is represented using the syntax:
arrayVar[rowIndex][columnIndex]
.
5.
You can create and initialize a two-dimensional array using an array initializer with the
syntax:
elementType[][] arrayVar = {{row values}, . . . , {row values}}
.
6.
You can use arrays of arrays to form multidimensional arrays. For example, a variable
for three-dimensional arrays can be declared as
elementType[][][] arrayVar
, and
a three-dimensional array can be created using
new elementType[size1][size2]
[size3]
.
T
EST
Q
UESTIONS
P
ROGRAMMING
E
XERCISES
*7.1
(
Sum elements column by column
) Write a method that returns the sum of all the
elements in a specified column in a matrix using the following header:
public static double
sumColumn(
double
[][] m,
int
columnIndex)
Write a test program that reads a 3-by-4 matrix and displays the sum of each col-
umn. Here is a sample run:
Enter a 3-by-4 matrix row by row:
1.5 2 3 4
5.5 6 7 8
9.5 1 3 1
Sum of the elements at column 0 is 16.5
Sum of the elements at column 1 is 9.0
Sum of the elements at column 2 is 13.0
Sum of the elements at column 3 is 13.0
*7.2
(
Sum the major diagonal in a matrix
) Write a method that sums all the numbers in
the major diagonal in an
n
*
n
matrix of integers using the following header:
public static double
sumMajorDiagonal(
double
[][] m)
Write a test program that reads a 4-by-4 matrix and displays the sum of all its ele-
ments on the major diagonal. Here is a sample run: