Lecture 8: 2D Arrays and Nested Loops Yoni Fridman 7/10/01
Outline Two-dimensional arrays Creating 2D arrays Using 2D arrays How 2D arrays are stored Examples
Two-dimensional Arrays Arrays in Java can have any number of dimensions. Yesterday we looked at one-dimensional arrays. Today we’ll look at two-dimensional arrays. 7 2 8 9 5 4 3 1 6
Creating 2D Arrays 2D arrays are declared just like 1D arrays, but with two pairs of square brackets: int[][] myGrid; Space is allocated for 2D arrays just like for 1D arrays, but again with two pairs of square brackets: myGrid = new int[rows][cols]; So this declares and allocates a 4 x 9 array, like shown in the last slide, but full of zeros. int[][] myGrid; myGrid = new int[4][9]; OR int[][] myGrid = new int[4][9];
Using 2D Arrays To access the highlighted array element, for example, we write myGrid[2][6]. What will this example do? columns 1 2 3 4 5 6 7 8 rows 1 2 3 7 2 8 9 5 4 3 1 6 3 myGrid[2][1] = 5; System.out.println(myGrid[2][0] * myGrid[2][1]);
How 2D Arrays Are Stored It’s intuitive to imagine a 2D array as a table, but Java actually stores it as an array of arrays. So myGrid.length == 4. And myGrid[0].length == myGrid[1].length == … == 9. myGrid 1 2 3 7 2 8 9 5 4 3 1 6 7 2 8 9 5 4 3 1 8 6 2 5 3 9 5 6 8 1 2 6 9 5 4
Examples Nested loop example: Displaying a pyramid. 2D array example: Summing a table.
Homework Read: 1.7, 2.3 (middle of p. 34 to middle of p. 36), 2.11, and on-line handout. Remember: HW3 due tomorrow at the beginning of class.