1. 2D arrays
Two dimensional Arrays
While the one dimensional array such as int[]
can be represented as a line, a two dimensional array int[][]
can be visualized as a grid. Usually, we refer to the first dimension as "rows" (the y axis) and the second dimension as columns (the x axis). This is how we create a two dimensional array:
public class MyProgram { public static void main(String[] args) { int[][] x = { {10,20},{30,40},{50,60} }; //When drawn on a piece of paper, this looks like: //10 20 //30 40 //50 60 int[][] y = { {1},{2,3},{4,5,6} }; //notice that the subarrays can be of different lengths. //y looks like: //1 //2 3 //4 5 6 int[][] z = new int[2][4]; //All values are by default zero in this initialization //z looks liks: //0 0 0 0 //0 0 0 0 } }
Indexing into two dimensional arrays
To get the first row and third column of an array int[][] nums
, we type nums[0][2]
. We can also set the value here with nums[0][2] = 5
. Additionally, these indices can be replaced with variables of type int. Thus, we can build this example that prints a two dimensional array:
public class MyProgram { public static void main(String[] args) { int[][] wat = { {10},{20,30},{40,50,60} }; for(int j = 0; j < wat.length ; j++) { //j is less than the # of ROWS (wat.length) for(int i = 0; i < wat[j].length; i++) {//i is less than the # of COLUMNS (wat[j].length) //note that because this is an irregular array //the number of columns changes depending on the row System.out.print(wat[j][i]); //print, unlike println, does not add a new line when run System.out.print(" "); //adds a space between columns } System.out.println(""); //adds a new line between rows } } }
Once we have this two dimensional loop, we can extend one dimensional algorithms to two dimensions. By placing an if statement in the inner most loop as well as two index variables, we can search for an item, locate the position of a maximum, locate the position of a minimum, and more. We can also sum up a two dimensional array by adding a sum variable before the loop. Other algorithms, such as matrix addition (adding one two dimensional array to another) may interact with two equally sized grids using the same two loops. All use these loops