Java Reference
In-Depth Information
int temp = matrix[i][j];
matrix[i][j] = matrix[i1][j1];
matrix[i1][j1] = temp;
}
}
8.5
Show the output 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();
}
8.6
Show the output 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);
8.4 Passing Two-Dimensional Arrays to Methods
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 8.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 8.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));
9 }
10
11 public static int [][] getArray() {
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
pass array
getArray method
 
 
 
Search WWH ::




Custom Search