A 2D array is an array of arrays, It can be thought of as having rows and columns such as a matrix with both row and column starting from 0.
To declare a 2D array, you need 2 sets of brackets and 2 size declarators.
double[][] heights = new double[4][300];
//This 2D array would contain 4 rows and 300 columns.
To initialize a 2D array using a list of values, you need to enclose each row's initialization list in its own set of braces.
int[][] numbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Nested loops are used in programs involving 2D arrays. The outer loop is used to traverse through rows while the inner loop is used to traverse through columns.
double[][] heights = new double[4][300];
Scanner in = new Scanner(new FileReader("inputData.txt"));
for (int row = 0; row < 4; row++){
for (int col = 0; col < 300; col++){
heights[row][col] = in.nextDouble();
}
}
Because 2D arrays are arrays of 1D arrays, the length of a 2D array is the number of rows. Because each row is a 1D array, the length of each row tells how many columns there are. Each row can also have a different number of columns which is called a ragged array.
Homework: https://docs.google.com/forms/d/e/1FAIpQLSeY-htm4sCcSxO9LPP4vFiFTCD2BOjMWs_12qWTqlJq-XIaJg/viewform?usp=sf_link