Chapter 5
Chapter 5
Multidimensional
Arrays
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 1
0132130807
Motivatio
ns
• Thus far, you have used one-dimensional arrays to model linear collections
of elements. You can use a two-dimensional array to represent a matrix or
a table. For example, the following table that describes the distances
between the cities can be represented using a two- dimensional array.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 2
0132130807
Objectiv
es
• To give examples of representing data using two-dimensional arrays
(§7.1).
• To declare variables for two-dimensional arrays, create arrays, and
access array elements in a two-dimensional array using row and
column indexes (§7.2).
• To program common operations for two-dimensional arrays
(displaying arrays, summing all elements, finding min and max
elements, and random shuffling) (§7.3).
• To pass two-dimensional arrays to methods (§7.4).
• To write a program for grading multiple-choice questions using
two-dimensional arrays (§7.5).
• To solve the closest-pair problem using two-dimensional arrays
(§7.6).
• To check a Sudoku solution using two-dimensional arrays (§7.7).
• To use multidimensional arrays (§7.8).
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 3
0132130807
Two-dimensional
Arrays
• A two-dimensional array is a one-dimensional array in which each element is another one-
dimensional array.
x[2]
x[2][0] x[2][1] x[2][2] x[2][3]
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 4
0132130807
• Multidimensional arrays can be initialized with array
initializers in declarations.
• A two-dimensional array b with two rows and two columns
could be declared and initialized with nested array
initializers as follows:
• int[][] b = {{1, 2}, {3, 4}};
• The initial values are grouped by row in braces.
• The number of nested array initializers (represented by
sets of braces within the outer braces) determines the
number of rows.
• The number of initializer values in the nested array
• The lengths of the rows in a two-dimensional array are not required to be the
same:
• int[][] b = {{1, 2},
{3, 4, 5}};
• Each element of b is a reference to a one-dimensional array of int variables.
• The int array for row 0 is a one-dimensional array with two elements (1 and 2).
• The int array for row 1 is a one-dimensional array with three elements (3, 4 and
5).
A multidimensional array with the same number of columns in every row can be created
with an array-creation expression.
int[][] b = new int[3][4];
3 rows and 4 columns.
The elements of a multidimensional array are initialized when the array object is
created.
A multidimensional array in which each row has a different
number of columns can be created as follows:
int[][] b = new int[2][]; // create 2 rows
b[0] = new int[5]; // create 5 columns for row 0
b[1] = new int[3]; // create 3 columns for row 1
Creates a two-dimensional array with two rows.
Row 0 has five columns, and row 1 has three columns.
Declare/Create Two-dimensional
Arrays
// Declare array ref var
dataType[][] refVar;
// Create array and assign its reference to variable
refVar = new dataType[10][10];
// Combine declaration and creation in one statement
dataType[][] refVar = new dataType[10][10];
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 8
0132130807
Declaring Variables of 2D Arrays and
Creating 2D Arrays
int matrix[][] = new int[10][10];
//OR
int[][] matrix = new int[10][10];
matrix[0][0] = 3;
double[][] x;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 9
0132130807
class HelloWorld
{
public static void main(String[] args)
{
//Single-Dimensinal Array //
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println("Single-Dimensinal Array");
for(int a: numbers) //Single Dimensinal Array//
{
System.out.println(a);
}
//Multi-Dimensinal Array //
int[][] array2D = {
{5, 2, 9},
{1, 7, 6},
{3, 8, 4}
};
System.out.println("Multi-Dimensinal Array");
for (int[] row : array2D) //Multi-Dimensinal Array row//
{
for (int elem : row) //Multi-Dimensinal Array column//
{
System.out.print(elem + " ");
}
System.out.println();
}
}
}
class HelloWorld
{
public static void main(String[] args)
{
int[][] array2D = {
{5, 2, 9},
{1, 7, 6},
{3, 8, 4}
};
System.out.println("Multi-Dimensinal Array");
// for (int[] row : array2D) //Multi-Dimensinal Array row//
for(int i=0; i< array2D.length;i++)
{
// for (int elem : row) //Multi-Dimensinal Array column//
for(int j=0; j< array2D[i].length; j++)
{
//System.out.print(elem + " ");
System.out.print(array2D[i][j] +" ");
}
System.out.println();
}
}
}
Two-dimensional Array
Illustration
int [] [] matrix = new int[5][5];
matrix[2][1] = 7;
matrix[3][4] = 7;
Caution
It is a common mistake to use matrix[2, 1] to access the element at row 2
and column 1. In Java, each subscript must be enclosed in a pair of
square brackets like this matrix[2][1]
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 12
0132130807
Declaring, Creating, and Initializing Using
Shorthand Notations
• You can also use an array initializer to declare, create and initialize a two-
dimensional array.
• For example,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 13
0132130807
Lengths of Two-dimensional
Arrays
• A two-dimensional array is an array in which each element is a
one-dimensional
array.
• The length of an array x is the number of elements in the
array, which can be obtained using x.length.
– the elements, x[0], x[1],….., and x[x.length-1], are arrays.
• Their lengths can be obtained using
– x[0].length, x[1].length, ……,and x[x.length-1].length.
– Arrayname.length
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 14
0132130807
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, x.length is 3, and
• x[0].length, x[1].length, and x[2].length are 4.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 15
0132130807
Lengths of Two-dimensional
Arrays, cont.
int[][] array = {
{1, 2, 3}, array.length = 4 this is the number of
{4, 5, 6, 4}, rows
{7, 8}, array[0].length = 3
{10, 11, 12, 5, 7} array[1].length = 4
}; array[2].length = 2
array[3].length = 5
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 16
0132130807
Ragged
Arrays
• Each row in a two-dimensional array is itself an array.
• So, the rows can have different lengths. Such an array is known
as a ragged array.
For example,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 17
0132130807
Ragged
Arrays,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 18
0132130807
Exercise Questions from text book
8.1 Declare an array reference variable for a two-dimensional array of int values,
create
a 4-by-5 int matrix, and assign it to the variable.
8.2 Can the rows in a two-dimensional array have different lengths?
8.3 What is the output of the following code?
int[][] array = new int[5][6];
int[] x = {1, 2};
array[0] = x;
System.out.println("array[0][1] is " + array[0][1]);
8.4 Which of the following statements are valid?
int[][] r = new int[2];
int[] x = new int[];
int[][] y = new int[3][];
int[][] z = {{1, 2}};
int[][] m = {{1, 2}, {2, 3}};
int[][] n = {{1, 2}, {2, 3}, };
8.5 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++)
for (int j = 0; j < array[i].length; j++)
sum += array[][j];
System.out.println(sum);
Processing Two-Dimensional
Arrays
• Initializing arrays with input values
• Printing arrays
• Summing all elements
• Summing all elements by column
• Which row has the largest sum
• Finding the smallest index of the
largest element
• Random shuffling
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 21
0132130807
public class TwoDimensionalArrayOperations
{ // Method to sum all elements in the array
public static void main(String[] args) { public static int sumElements(int[][] array) {
// Create a 2D array int sum = 0;
int[][] array2D = { for (int[] row : array) {
{5, 2, 9}, for (int elem : row) {
{1, 7, 6}, sum += elem;
{3, 8, 4} }
}; }
// Display the array return sum;
System.out.println("Original Array:"); }
displayArray(array2D); }
// Sum all elements
int sum = sumElements(array2D); OUTPUT:-
System.out.println("Sum of all elements: " + sum); Original Array:
} 529
// Method to display the array 176
public static void displayArray(int[][] array) { 384
for (int[] row : array) { Sum of all elements: 45
for (int elem : row) {
System.out.print(elem + " ");
}
System.out.println();
}
}
Processing Two-Dimensional Arrays:
Examples
//Initializing arrays with input values
java.util.Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + "
rows and " +
matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = input.nextInt();
}
}
//Initializing arrays with random values
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = (int)(Math.random() * 100);
}
}
//Printing arrays
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 23
0132130807
Summing 2D
Array
//Summing all elements
int total = 0;
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
total += matrix[row][column];
}
}
System.out.println("Sum for row " + row+ " is " + total);
//Summing elements by line
for (int row = 0; row < matrix.length; row++) {
int total = 0;
for (int column = 0; column <
matrix[row].length; column++) {
total += matrix[row][column];
}
System.out.print ("Sum for row" + row+ " is "
+ total);
}
// Summing elements by column
for (int column = 0; column < matrix[0].length; column++) {
int total = 0;
for (int row = 0; row < matrix.length; row++){
total += matrix[row][column];
}
System.out.print ("Sum for column" + column+ " is
" + total);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 24
} 0132130807
Write a Java program to multiply two matrices.
public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,2,3},{4,5,6},{7,8,9}};
for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
c[i][j] = a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}
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.
• 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.
• Question:
• 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.
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[2][3]; // Enter array values
System.out.println("Enter " + m.length + " rows and “ + m[0].length + " columns: ");
for (int i = 0; i < m.length; i++) //row//
for (int j = 0; j < m[i].length; j++) //column//
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;
}
}
8.7 Show the size of array:
public class Test {
public static void main(String[] args) {
int[][] array = {{1, 2, 3. 4},
{5, 6, 7, 8}};
System.out.println(m1(array)[0]);
System.out.println(m1(array)[1]);
}
public static int[] m1(int[][] m)
{
int[] result = new int[2];
result[0] = m.length; // row
result[1] = m[0].length; //column
return result;
}
}
OUTPUT:
2
4
WAP to check the grade of students answers by the array key
public class GradeExam {
/** Main method */
public static void main(String[] args)
// Grade all answers
{
for (int i = 0; i < answers.length; i++) {
// Students' answers to the questions
// Grade one student
char[][] answers = {
int correctCount = 0;
{'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
for (int j = 0; j < answers[i].length; j++) {
{'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'},
if (answers[i][j] == keys[j])
{'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'},
correctCount++;
{'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'},
}
{'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
System.out.println("Student " + i + "'s correct count is " + correctCount);
{'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
}
{'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
}
{'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}};
}
// Key to the questions
char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};
Multidimensional
Arrays
• Occasionally, you will need to represent n-dimensional data structures.
In Java, you can
create n-dimensional arrays for any integer n.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 31
0132130807
Multidimensional
Arrays
double[][][] scores = {
{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},
{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},
{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},
{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},
{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}};
scores[ i ] [ j ] [ k ]
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 32
0132130807
Problem: Calculating Total
Scores
• Objective: write a program that calculates the total score for
students in a class.
• Suppose the scores are stored in a three-dimensional array
named scores.
• The first index in scores refers to a student, the second refers
to an exam, and the third refers to the part of the exam.
Suppose there are 7 students, 5 exams, and each exam has
two parts--the multiple-choice part and the programming part.
• So, scores[i][j][0] represents the score on the multiple-choice part
for the i’s student on the j’s exam. Your program displays the
total score for each student.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 33
0132130807
WAP to display 2D Array & find the minimum, maximum & sum of the 2D Array elements
import java.util.Random; // Method to find the maximum element in the array
public class TwoDimensionalArrayOperations public static int findMax(int[][] array)
{
{ int max = Integer.MIN_VALUE;
public static void main(String[] args) { for (int[] row : array) {
int[][] array2D = {{5, 2, 9},{1, 7, 6},{3, 8, 4} }; for (int elem : row) {
System.out.println("Original Array:") if (elem > max) {
displayArray(array2D); max = elem;
// Find min max & sum elements }
}
int min = findMin(array2D); }
System.out.println("Minimum element: " + min); return max;
int max = findMax(array2D); }
System.out.println("Maximum element: " + max); // Method to calculate the sum of all elements
int sum = calculateSum(array2D); public static int calculateSum(int[][] array)
System.out.println("Sum of all elements: " + sum); {
int sum = 0;
} for (int[] row : array) {
for (int elem : row) {
// Method to find the minimum element in the array sum += elem;
public static int findMin(int[][] array) { }
int min = Integer.MAX_VALUE; }
return sum;
for (int[] row : array) {
}
for (int elem : row) { // Method to display the array
if (elem < min) { OUTPUT:-
public static void displayArray(int[][] array) {
min = elem; for (int[] row : array) {
Original Array:
} for (int elem : row) { 529
} System.out.print(elem + " "); 176
} } 384
System.out.println(); Minimum element: 1
return min; }
} Maximum element: 9
}
}
Sum of all elements: 45
Any
Questions?
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
0132130807