Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java.

6
Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java

Transcript of Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java.

Page 1: Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java.

Two dimensional arrays in Java

Computer Science 3

GerbObjective: Use matrices in Java

Page 2: Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java.

Array dimensions

• Arrays we have studied so far can be arranged in a line

• In this respect they could be thought of as “one dimensional”

• In Java, it is possible to have arrays of more than one dimension.

0 1 2 3 4 5 6 7

Page 3: Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java.

Two dimensional arrays• A 2-dimensional array is sometimes called a ______

• Instead of one _____, each element has two– First could be though of as a “___”

– Second could be thought of as a “______”

0 1 2 3

0

1

2

3

Page 4: Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java.

Using two-dimensional arrays• Identify by placing two sets of open and close square

brackets ([][]) after the ____– Recall that an array type has one set of open and close square

brackets

– When you declare, put the number of _____and________ in between the brackets after the type that follows new:

int[][] myMatrix = new int[5][7];

• Identify an array element by placing the two indexes each between its own ______________________:– As always, columns and rows start numbering at zero

– This would print the element in the 5th row and 4th column:

System.out.print(myMatrix[4][3]);

Page 5: Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java.

How two dimensional arrays are stored

• Two dimensional arrays are stored as an “_______________”

• In the following example:int[][] myMatrix = new int[4][6];

• myMatrix[2] would be a one dimensional array of length 6.

• myMatrix[2][0] would be the first element in that array– i.e. the first element in the 3rd row of the matrix

Page 6: Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java.

Initializing two dimensional arrays

• Can initialize a two dimensional array– Put each row in ________– Separate elements and rows by ______– Put brackets around ________

• Example:int[][] mySquare = {{8,1,6}, {3,5,7}, {4,9,2}};