Unit 8 - 2D Array Flashcards
2D array
An array of arrays
Can be better way to store data
Exp - seating chart of students
Rectangular 2D array
Each row array has same number of elements
Declaring a 2D array
DataType [ ] [ ] nameOf2DArray
Initializing a 2D array
Needs to know # of rows and columns
new DataType [r] [c]
If you know what elements of 2D arrrays you want to include, you can
initialize the 2D array with a set of initializer lists
Initializer lists
Starts & ends with curly brackets {}
Each row has its own initializer list
Separating elements and initializer lists with commas
{{“Alice”,”Rob”,”Cody”},{“Robin”,”Becky”,”Kisha”}}
We refer to 2D array’s size by
# of rows along with # of columns r by c
How to determine number of rows in a 2D array
r = grades.length
How to determine number of column in a 2D array
c = grades[0].length
How to access an element in a 2D array
name of array variable
2 sets of square brackets
index of row where element is located
index of row where element is located
grade [5,2]
How to access an element in a 2D array
grade [5,2] = grade [5,2] + 1
How to create a new 2D array
DataType [ ] [ ] nameOf2DArray = new DataType [r][c];
String [ ] [ ] seating = new String [10][3}
In order to print out the contents of a 2D array,
you need to use for loops inside of for loops
In order to print out the contents of a 2D array, and you don’t know the specific dimensions,
you need to use
nameOf2DArray.length for row and
nameOf2DArray [0].length for column
Nested iteration statements can be written to traverse 2D array in
row-major order or column-major order