INTRODUCTION TO
JAVA PROGRAMMING
Chapter 7: Multidimensional Arrays 1
Introduction
• Data in a table or a matrix can be represented using a two-
dimensional array.
• For example, the following table that lists the distances between
cities can be stored using a two-dimensional array named distances
2
Two-Dimensional Array Basics: creation/declaration
• The syntax for declaring a 2D-array variable is:
• Example:
• You can create a 2D array of 5-by-5 int values and assign it
to matrix using this syntax:
• An element in a two-dimensional (2D) array is accessed
through a row and column index. 3
Combine declaration and creation
• Combine declaration and creation in one statement
dataType[][] refVar = new dataType[10][10];
• Alternative syntax
dataType refVar[][] = new dataType[10][10];
• Example:
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
4
Two-dimensional Array Illustration
• Two subscripts are used in a two-dimensional array, one for
the row and the other for the column. The index for each
subscript is of the int type and starts from 0:
• To assign the value 7 to a specific element at row 2 and
column 1, you can use the following syntax:
5
Declaring, Creating, and Initializing Using Shorthand
Notations
• You can also use an array initializer to declare, create, and
initialize a two-dimensional array.
6
Obtaining the Lengths of Two-Dimensional Arrays
• A 2D-array is actually an array in which each element is a 1D array.
• The length of an array x is the number of elements in the array, which
can be obtained using x.length.
• x[0], x[1], . . . , x[x.length-1] are arrays. Their lengths can be obtained
using x[0].length, x[1].length, . . . , and x[x.length-1].length
• Suppose x = new int[3][4];
x[0], x[1], and x[2] are 1D arrays and each contains 4 elements,
- 𝑥. 𝑙𝑒𝑛𝑔𝑡ℎ = 3
- 𝑥[0]. 𝑙𝑒𝑛𝑔𝑡ℎ = 𝑥[1]. 𝑙𝑒𝑛𝑔𝑡ℎ = 𝑥[2]. 𝑙𝑒𝑛𝑔𝑡ℎ = 4 7
Ragged Arrays
• Each row in a 2D array is itself an array. Thus, the rows can have
different lengths. An array of this kind is known as a ragged array.
• As you can see,
– triangleArray[0].length = 5,
– triangleArray[1].length is 4,
– triangleArray[2].length is 3,
– triangleArray[3].length is 2,
– and triangleArray[4].length is 1. 8
Ragged Arrays, cont.
• If you don’t know the values in a ragged array in advance, but do
know the sizes—say, the same as before—you can create a ragged
array using the following syntax:
• You can now assign values to the array. For example,
• Note
The syntax new int[5][ ] for creating an array requires the first
index to be specified. The syntax new int[ ][ ]would be wrong.
9
Processing Two-Dimensional Arrays
• Nested for loops are often used to process a 2D array.
• Suppose an array matrix is created as follows:
int[][] matrix = new int[10][10];
The following are some examples of processing arrays.
1. Initializing arrays with user input values.
2. Initializing arrays with random values.
3. Printing arrays.
4. Summing all elements.
5. Summing all elements by column
6. Which row has the largest sum?
7. Random shuffling. 10
Initializing arrays with user input values
• The following loop initializes the array with user input values:
int[][] matrix = new int[10][10];
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] Does this apply to a ragged array?
[0] 0 0 0 0 0 0 0 0 0 0
[1] 0 0 0 0 0 0 0 0 0 0
[2] 0 0 0 0 0 0 0 0 0 0
[3] 0 0 0 0 0 0 0 0 0 0
[4] 0 0 0 0 0 0 0 0 0 0
[5] 0 0 0 0 0 0 0 0 0 0
[6] 0 0 0 0 0 0 0 0 0 0
[7] 0 0 0 0 0 0 0 0 0 0
[8] 0 0 0 0 0 0 0 0 0 0
[9] 0 0 0 0 0 0 0 0 0 0 11
Initializing arrays with random values
• The following loop initializes the array with random values
between 0 and 99:
Does this apply to a ragged array?
12
Printing arrays
• To print a 2D array, you have to print each element in the
array using a loop like the following:
Does this apply to a ragged array?
13
Summing all elements.
• Use a variable named total to store the sum. Initially total
is 0. Add each element in the array to total using a loop as
follows:
Does this apply to a ragged array?
14
Summing elements by column.
• For each column, use a variable named total to store its
sum. Add each element in the column to total using a loop:
int[][] matrix = new int[10][10];
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
[0] 0 0 0 0 0 0 0 0 0 0
[1] 0 0 0 0 0 0 0 0 0 0
Does this apply to a ragged array? [2] 0 0 0 0 0 0 0 0 0 0
[3] 0 0 0 0 0 0 0 0 0 0
[4] 0 0 0 0 0 0 0 0 0 0
[5] 0 0 0 0 0 0 0 0 0 0
[6] 0 0 0 0 0 0 0 0 0 0
[7] 0 0 0 0 0 0 0 0 0 0
[8] 0 0 0 0 0 0 0 0 0 0
[9] 0 0 0 0 0 0 0 0 0 0 15
Which row has the largest sum?
• Variables maxRow and indexOfMaxRow track the largest sum
and index of the row.
Does this apply to a ragged array?
16
Random shuffling.
• For each element matrix[i][j], randomly generate indices i1 and
j1 and swap matrix[i][j] with matrix[i1][j1], as follows:
matrix[i1].length
• Does this apply to a ragged array?
• If no, what is the required modification?
17
Passing Tow-Dimensional Arrays to Methods
• When passing a 2D array to a method, the reference of the
array is passed to the method (like for 1D arrays).
• Below an example with 2 methods:
– getArray(), returns a 2D array,
– sum(int[][] m), returns the sum of all the elements in a matrix.
18
Passing Tow-Dimensional Arrays to Methods
Run 19
Case Study: Grading a Multiple-Choice Test
• Suppose you need to write a program that grades multiple-choice
tests. Assume there are 8 students and 10 questions, and the
answers are stored in a 2D array. Each row records a student’s
answers to the questions, as shown below.
• The key is stored in a 1D array:
20
Case Study: Grading a Multiple-Choice Test
Run
21
Case Study: Finding the Closest Pair
• Given a set of points, the closest-pair problem is to find the
two points that are nearest to each other.
• In the figure, for example, points (1, 1) and (2, 0.5) are
closest to each other.
• An intuitive way to solve this problem is to compute the
distances between all pairs of points and find the one with
the minimum distance. 22
Case Study: Finding the Closest Pair
23
Case Study: Finding the Closest Pair
for (int i = 0; i < points.length-1; i++) {
Run
24
What is Sudoku?
• Sudoku is a grid divided into smaller boxes (also called
regions or blocks), as shown in a. Some cells, called fixed
cells, are populated with numbers from 1 to 9.
• The objective is to fill the empty cells, called free cells, with
the numbers 1 to 9 so that every row, every column, and
every 3 3 box contains the numbers 1 to 9, as shown in b.
25
Every row contains the numbers 1 to 9
5 3 7 5 3 4 6 7 8 9 1 2
6 1 9 5 6 7 2 1 9 5 3 4 8
9 8 6 1 9 8 3 4 2 5 6 7
8 6 3 8 5 9 7 6 1 4 2 3
4 8 3 1 4 2 6 8 5 3 7 9 1
7 2 6 7 1 3 9 2 4 8 5 6
6 9 6 1 5 3 7 2 8 4
4 1 9 5 2 8 7 4 1 9 6 3 5
8 7 9 3 4 5 2 8 6 1 7 9
26
Every column contains the numbers 1 to 9
5 3 7 5 3 4 6 7 8 9 1 2
6 1 9 5 6 7 2 1 9 5 3 4 8
9 8 6 1 9 8 3 4 2 5 6 7
8 6 3 8 5 9 7 6 1 4 2 3
4 8 3 1 4 2 6 8 5 3 7 9 1
7 2 6 7 1 3 9 2 4 8 5 6
6 9 6 1 5 3 7 2 8 4
4 1 9 5 2 8 7 4 1 9 6 3 5
8 7 9 3 4 5 2 8 6 1 7 9
27
Every 3×3 box contains the numbers 1 to 9
5 3 7 5 3 4 6 7 8 9 1 2
6 1 9 5 6 7 2 1 9 5 3 4 8
9 8 6 1 9 8 3 4 2 5 6 7
8 6 3 8 5 9 7 6 1 4 2 3
4 8 3 1 4 2 6 8 5 3 7 9 1
7 2 6 7 1 3 9 2 4 8 5 6
6 9 6 1 5 3 7 2 8 4
4 1 9 5 2 8 7 4 1 9 6 3 5
8 7 9 3 4 5 2 8 6 1 7 9
28
Checking whether a Solution Is Correct
• This is a very challenging problem.
• This section presents a simplified version of the Sudoku
problem, which is to verify whether a solution is correct.
5 3 7 5 3 4 6 7 8 9 1 2
6 1 9 5 6 7 2 1 9 5 3 4 8
9 8 6 1 9 8 3 4 2 5 6 7
8 6 3 8 5 9 7 6 1 4 2 3
4 8 3 1 4 2 6 8 5 3 7 9 1
7 2 6 7 1 3 9 2 4 8 5 6
6 9 6 1 5 3 7 2 8 4
4 1 9 5 2 8 7 4 1 9 6 3 5
8 7 9 3 4 5 2 8 6 1 7 9
29
Sudoku (verification) implementation
• Once a solution to a Sudoku puzzle is found, how do you
verify that it is correct? Here are two approaches:
1. Check if every row has numbers from 1 to 9, every column has
numbers from 1 to 9, and every small box has numbers from 1 to
9.
2. Check each cell. Each cell must be a number from 1 to 9 and the
cell must be unique on every row, every column, and every small
box.
30
Sudoku implementation: Checking Whether a Solution Is Correct
31
Sudoku implementation: Checking Whether a Solution Is Correct
Run
Should be OR:(row !=i || col !=j)&& ...
32
Multidimensional Arrays
• A 2D array consists of an array of 1D arrays and a 3D array consists of
an array of 2D arrays.
• In Java, you can create n-dimensional arrays for any integer n.
• For exp., you may use a 3D array to store exam scores for a class of 6
students with 5 exams, and each exam has 2 parts (multiple-choice
and essay). The following syntax declares a 3D array variable scores,
creates an array, and assigns its reference to scores.
• You can also use the short-hand notation to create and initialize the
array as follows:
33
Multidimensional Arrays
• scores[0][1][0] refers to the “multiple-choice” score for the first
student’s second exam, which is 9.0.
• scores[0][1][1] refers to the “essay score” for the first student’s
second exam, which is 22.5.
• This is depicted in the following figure:
34
Multidimensional Arrays
• A multidimensional array is actually an array in which each element is
another array:
– A 3D array consists of an array of 2D arrays.
– A 2D array consists of an array of 1D arrays.
35
Multidimensional Arrays
• For example, suppose x = new int[2][2][5],
– x[0] and x[1] are 2D arrays
– x[0][0], x[0][1], x[1][0], and x[1][1] are 1D arrays and each
contains 5 elements
• x.length is 2
• x[0].length and x[1].length are 2
• X[0][0].length, x[0][1].length, x[1][0].length, and x[1][1].length are 5
36
Case Study: Daily Temperature and Humidity
• Suppose a meteorology station records the temperature and
humidity every hour of every day and stores the data for the past 10
days in a text file Weather.txt.
• Each line of the file consists of 4 numbers that indicate the day, hour,
temperature, and humidity. The contents of the file may look like the
one in (a).
• Note that the lines in the file are not necessarily in increasing order
of day and hour. For example, the file may appear as shown in (b).
Weather.txt 37
Case Study: Daily Temperature and Humidity
• Your task is to write a program that calculates the average
daily temperature and humidity for the 10 days stored in a
3D array named data.
• 1st index of data ranges from 0 to 9 and represents 10 days,
• 2nd index ranges from 0 to 23 and represents 24 hours,
• 3rd index ranges from 0 to 1 and represents temp. and humidity
38
Case Study: Daily Temperature and Humidity
Weather.txt
39
Case Study: Daily Temperature and Humidity
Run
40
Case Study: Guessing Birthdays
41
Case Study: Guessing Birthdays
Run 42
Homework
• Study all materials in chapter 7 from the textbook.
• Exercises:
7.1, 7.2, 7.5, 7.6, 7.7, 7.8, 7.9, 7.10, 7.11, 7.13, 7.14,
7.16, 7.17, 7.19, 7.20, 7.25, 7.27,7.30, 7.31, 7.32,
7.33, 7.35, 7.36
from chapter 7
43