// 1 Dimensional Array Traversal
for (int value : array)
{
if (value ....)
...
}
for(int i=0; i < array.length; i++)
{
if (array[i] ....)
...
}
But with 2D arrays, you will need to use nested loops to traverse the rows and columns of the 2D array. We often use indexed for loops for this to better control the row and column index values, but you can also use enhanced for loops.
What will the following code print out? Can you complete the method called getTotalForCol that gets the total for a column? To do this, you must loop through the rows. The arrayβs length will tell you how many rows you have since it is an array of arrays, while the length of the arrayβs first element will tell you how many columns.
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. Check your solution by clicking on the Check button. You will be told if any of the blocks are in the wrong order.
public int getLargest(int[][] arr)
{
---
int largest = arr[0][0];
int current = 0;
for(int r=0;r < arr.length;r++)
{
---
for(int c=0;c < arr[0].length;c++)
{
---
current = arr[r][c];
if (current > largest)
{
---
largest = current;
---
} // end if
---
} // end column loop
---
} // end row loop
return largest;
---
} // end method
Subsection4.13.2Subsection of a 2D Array for a Property
You can loop through just part of a 2D array. You can change the starting value and ending value to loop through a subset of a 2D array. The following code counts the number of times a value appears in a part of the 2D array indicated by the row and column start and end values.
You can determine the presence or absence of duplicate elements in the 2D array or in a designated row, column, or other subsection. With 1D arrays, we sometimes needed 2 nested loops to check for duplicates or pairs. With 2D arrays, you often need 4 nested loop to check the whole array!
The method noDups(nums) returns true if there are no repeated (duplicate) items in the array nums. It should return false if it does find a repeated element using nested loops.
We can also rotate or reverse the order of the elements in a row or column. The following code rotates the elements in a row to the right by one position. This algorithm is very similar to the 1D array rotation algorithm since we are dealing with a single row or column.
Subsection4.13.5Review and FRQ Practice with 2D arrays
This lesson ends the 2D arrays section of this unit. You can now do the following review lessons and FRQs at the end of the unit and College Board Progress Checks in the AP Classroom.
We encourage you to work in pairs or groups to tackle the following challenging FRQ problems and take them one step at a time. These will get easier with practice!