Multi-Dimensional Arrays in Java

Download Report

Transcript Multi-Dimensional Arrays in Java

Multi-Dimensional Arrays in Java
"If debugging is the process of removing software bugs, then
programming must be the process of putting them in."
-- Edsger Dijkstra
Plan for today:
•
•
•
* multi-dimensional arrays (mostly 2D)
* array creation and traversal
* accessing rows and columns in a 2D array
Array Creation
When we create an array in Java, the number of pairs of
square brackets indicates the dimensions of the array. So
far, we’ve only used one-dimensional arrays:
• int[] arr = new int[10];
• 2D array of integers:
• int[][] matrix = new int[4][3];
• // 4 rows, 3 columns
• 3D array of integers:
• int[][][] arr2 = new int[3][5][2];
2D Arrays
• int[][] matrix = new int[4][3];
• Making sense of it all:
• matrix is a reference to the entire array
• matrix[i][j] is for the entry in row i, column j
• indexing for both rows and columns starts at 0
• matrix[0][0] is the int in the first row and first
column
• matrix[i] refers to row i
• matrix[0] refers to the first row, or the row with
index 0
• No way of referencing a column
2D Arrays
• int[][] matrix = new int[3][2];
0
1
0
0
0
1
2
row
0
0
0
0
matrix
column
• Reasonable way to visualize 2-dimensional array
• Remember: array entries are automatically initialized
• arrays of numbers: entries initialized to 0
2D Array Examples
• Write a method that takes a 2D array of ints, and prints
the array’s elements in row order - that is, first print the
elements in row 0, then row 1, then row 2, etc.
• Write a method that takes a 2D array of doubles, and
returns the maximum value in the array.