60 likes | 161 Vues
2-D Arrays. CSC 202. A Brief Introduction to Two-Dimensional Arrays. An example of declaring a one-dimensional array that can contain 5 integers: int [ ] example = new int [5]; An example of declaring a two-dimensional array: int [ ] [ ] twoD = new int [3] [5];
E N D
2-D Arrays CSC 202
A Brief Introduction to Two-Dimensional Arrays • An example of declaring a one-dimensional array that can contain 5 integers: • int [ ] example = new int [5]; • An example of declaring a two-dimensional array: • int [ ] [ ] twoD = new int [3] [5]; • This example creates a two-dimensional array that has 3 rows and 5 columns.
Filling a 2-D Array • So, if the array were filled with the value 9 in each position, it could be thought of as appearing like this in memory: 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
Filling a 2-D Array • Suppose you fill the array using these loops: • for ( inti=0, i < twoD.length, i++) for (int j=0, j < twoD [i].length, j++) twoD [i] [j] = i + j; • What would the array look like in memory?
A Program For You //M. M. Pickard 1/27/2011 /* This program declares a 2-D array, fills it with values, and displays its contents. It can be found at ftp://cobweb.sfasu.edu/csc/mpickard/ftp/CSC202/TwoD_ArrayExample.java */ public class TwoD_ArrayExample{ public static void main (String args[]){ int[ ] [ ] twoD = new int [3] [5]; // declares a table with three rows and five columns for ( inti=0; i < twoD.length; i++) // iterates over all rows for (int j=0; j < twoD [i].length; j++) // iterates over all columnstwoD [i] [j] = i + j; // inserts a value at the intersection of the ith row and the jth column for ( inti=0; i < twoD.length; i++){ // iterates over all rows for (int j=0; j < twoD [i].length; j++) // iterates over all columns System.out.print(twoD[i] [j] + " "); //displays an element found in the ith row and the jthcol System.out.println(); // goes to a new line at the end of each row } // end for } // end main } // end class
Important Concepts • Arrays of Arrays • Ragged Arrays • Multidimensional Arrays