Intro | Declaring, Initializing | Accessing, Updating | Traversing | Algorithms |
Unit 8 - 2D Arrays Declaring and Initializing
2D Arrays Lesson
How to declare/initialize 2D arrays
// Boiler Plate Code public class Main { public static void main(String[] args) {
*/ (Intialize Array Here) */
// Display Array Code below
for(int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
} }
Main.main(null) 1) All in one
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
2) Empty array and manual input with indexes
// Declare a 3x3 empty 2D array
int[][] matrix = new int[3][3];
// Assign values to the 2D array using indexes
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;
3) Nested For-Loop
int value = 1; // Start value
for (int i = 0; i < matrix.length; i++) { // Outer loop for rows
for (int j = 0; j < matrix[i].length; j++) { // Inner loop for columns
matrix[i][j] = value++; // Assign value and increment
}
}
Popcorn Hack 1 (Part 1):
- Intialize a 2D array of the people in your group grouped based on pairs with 3 different methods
- ex Array: [[Anusha, Vibha],[Avanthika, Matthew]]
Ragged Arrays
Ragged Arrays (College Board Standard):
- non-rectangular array with different number of coloms in each row
- Also called non-rectangular, assymetric, or jagged arrays ~~~ // Code to create the Ragged Array itself (intialize with one of 3 methods)
int[][] raggedArray = new int[3][]; // Outer array with 3 rows
// Assign each row with different lengths raggedArray[0] = new int[2]; // 1st row has 2 columns raggedArray[1] = new int[4]; // 2nd row has 4 columns raggedArray[2] = new int[3]; // 3rd row has 3 columns ~~~
Popcorn Hack #2:
Output a number keypad (numbers 0-9)
- Create a ragged array (for each row of the keypad)
- Populate array with nested for loop
- Just use the numbers (0-9) (no special symbols for the keypad)