Introduction to Java_chapter7
Introduction to Java_chapter7
MULTIDIMENSIONAL
ARRAYS
١
Introduction
Data in a table or a matrix can be represented
using a two-dimensional array. For example:
٢
Two-Dimensional Array Basics
Declaring Variables of Multidimensional Arrays and
Creating Multidimensional Arrays
٣
Multidimensional Array
Illustration
0 1 2 3 4 0 1 2 3 4 0 1 2
0 0 0 1 2 3
6
1 1 1 4 5
2 2 7 2 7 8 9
3 3 3 10 11 12
4 4 int[][] array = {
{1, 2, 3},
matrix = new int[5][5]; matrix[2][1] = 7; {4, 5, 6} ,
{7, 8, 9},
{10, 11, 12}
};
٤
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use a shorthand notation to declare, create and initialize a two-
dimensional array. For example,
٥
Obtaining the Lengths of Two-
Dimensional Arrays
For example, suppose x = new int[3][4], x[0], x[1], and x[2] are
one-dimensional arrays and each contains four elements, as
shown in below Figure. x.length is 3, and x[0].length,
x[1].length, and x[2].length are 4.
The syntax new int[5][ ] for creating an array requires the first index
to be specified.
The syntax new int[ ][ ] would be wrong.
٨
Processing Two-Dimensional
Arrays
Suppose an array matrix is created as follows:
int[ ][ ] matrix = new int[10][10];
٩
Processing Two-Dimensional
Arrays, cont.
The following loop initializes the array with random values between
0 and 99:
١٠
Processing Two-Dimensional
Arrays, cont.
Printing arrays. To print a two-dimensional array, you have to print
each element in the array using a loop like the following:
١١
Processing Two-Dimensional
Arrays, cont.
The following loop for summing elements by column in array.
١٢
Passing Two-Dimensional Arrays to Methods
import java.util.Scanner;
public class PassTwoDimensionalArray {
public static void main(String[] args) {
Int [ ][ ] m = getArray(); // Get an array
System.out.println("\nSum of all elements is " + sum(m)); // Display sum of elements
}
public static int [ ][ ] getArray() {
Scanner input = new Scanner(System.in); // Create a Scanner
Int [ ][ ] m = new int[3][4];
System.out.println("Enter " + m.length + " rows and "+ m[0].length + " columns: ");
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[i].length; j++)
m[i][j] = input.nextInt();
return m;
}
public static int sum(int [ ][ ] m) {
int total = 0;
for (int row = 0; row < m.length; row++) {
for (int column = 0; column < m[row].length; column++) {
total += m[row][column];
}
}
return total;
}
١٣
}
Passing Two-Dimensional Arrays to
Methods, cont.
١٤