DC111 Data Structures What is a 2D Array? • The two dimensional or double-subscripted array can be represented as a table with rows and columns. In other words, a double-subscripted array is used when data is represented using a table. • It requires two subscripts to identify a particular element. By convention, the first subscript identifies the element’s row and the second identifies the element’s column.
Prepared by: Dr. Cheryl B. Pantaleon
DC111 Data Structures Declaration • Syntax: datatype[][] arrayName; datatype[][] arrayName = new dataType[rowSize][columnSize]; • Example: int[][] table = new int[3][4]; • Illustration:
Prepared by: Dr. Cheryl B. Pantaleon
DC111 Data Structures Initializing a 2D Array: Another Way • Example:
DC111 Data Structures Accessing Elements of a 2D Array 1. By the individual elements Example: table[2][1] = 6; System.out.println(table[2][1]); 2. Using a nested-loop Example: for(int i=0;i<3;i++){ for(int j=0;j<4;j++) System.out.print(table[i][j] + " "); System.out.println(); } • By convention, in accessing elements in a 2D array, nested-loop is used. The outer loop is the row counter while the inner loop is the column counter. Prepared by: Dr. Cheryl B. Pantaleon DC111 Data Structures Important Note • A two-dimensional array in Java is simply an array of a one- dimensional array.