Java Reference
In-Depth Information
✓
✓
7.5
Show the printout of the following code:
Check
Point
int
[][] array = {{
1
,
2
}, {
3
,
4
}, {
5
,
6
}};
for
(
int
i = array.length -
1
; i >=
0
; i——) {
for
(
int
j = array[i].length -
1
; j >=
0
; j——)
System.out.print(array[i][j] +
" "
);
System.out.println();
}
7.6
Show the printout of the following code:
int
[][] array = {{
1
,
2
}, {
3
,
4
}, {
5
,
6
}};
int
sum =
0
;
for
(
int
i =
0
; i < array.length; i++)
sum += array[i][
0
];
System.out.println(sum);
When passing a two-dimensional array to a method, the reference of the array is
passed to the method.
Key
Point
You can pass a two-dimensional array to a method just as you pass a one-dimensional array.
You can also return an array from a method. Listing 7.1 gives an example with two methods.
The first method,
getArray()
, returns a two-dimensional array, and the second method,
sum(int[][] m)
, returns the sum of all the elements in a matrix.
L
ISTING
7.1
PassTwoDimensionalArray.java
1
import
java.util.Scanner;
2
3
public class
PassTwoDimensionalArray {
4
public static void
main(String[] args) {
5
int
[][] m = getArray();
// Get an array
get array
6
7
// Display sum of elements
8 System.out.println(
"\nSum of all elements is "
+
sum(m)
);
pass array
9 }
10
11
12
// Create a Scanner
13 Scanner input =
new
Scanner(System.in);
14
15
// Enter array values
16
int
[][] m =
new int
[
3
][
4
];
17 System.out.println(
"Enter "
+ m.length +
" rows and "
18 + m[
0
].length +
" columns: "
);
19
for
(
int
i =
0
; i < m.length; i++)
20
for
(
int
j =
0
; j < m[i].length; j++)
21 m[i][j] = input.nextInt();
22
23
24 }
25
26
27
int
total =
0
;
28
for
(
int
row =
0
; row < m.length; row++) {
29
for
(
int
column =
0
; column < m[row].length; column++) {
30 total += m[row][column];
31 }
public static int
[][] getArray() {
getArray
method
return
m;
return array
public static int
sum(
int
[][] m) {
sum
method