Getting the Number of Rows and Columns¶

Arrays know their length (how many elements they can store). It is a public read-only field so you can use dot-notation to access the field (arrayName.length). The length of the outer array is the number of rows and the length of one of the inner arrays is the number of columns. Note that length is a field and not a method, so you don’t add parentheses after length. However, if you use parentheses after length during the exam, you won’t lose any points.

ticketInfo.length // returns the number of rows
ticketInfo.length // returns the number of columns


9-3-1: How many rows does a have if it is created as follows int[][] a = {{2, 4, 6, 8}, {1, 2, 3, 4}};?

9-3-2: Which of the following would I use to get the value in the third row and second column from a 2D array called nums?

Looping Through a 2D Array¶

Since you can find out the number of rows and columns in a 2D array you can use a nested for loop (one loop inside of another loop) to loop through all of the elements of a 2D array.

public static double getAverage(int[][] a)
{
double total = 0;
for (int row = 0; row < a.length; row++)
{
for (int col = 0; col < a.length; col++)
{
total = total + a[row][col];
}
}
}


• total is declared to be a double so that the result will be a double. If total was declared to be an int then the result would be an integer and the values after the decimal point would be thrown away.
• The number of rows is a.length
• The number of columns is a.length
• The number of times this loop executes is the number of rows times the number of columns.

Mixed up programs

9-3-3: The following has the correct code to find the largest value in a 2D array. Drag the blocks from the left into the correct order on the right and indent them as well. Check your solution by clicking on the Check Me button. You will be told if any of the blocks are in the wrong order or have the wrong indention.

Use a For-Each to Loop Through an Array¶

Since 2D arrays are really arrays of arrays you can also use a nested for-each loop to loop through all elements in an array.

public static double getAvg(int[][] a)
{
double total = 0;
for (int[] colArray : a)
{
for (int val : colArray)
{
total = total + val;
}
}