2D - Traversing 2D Arrays (Lesson)
Traversing 2D Arrays
Introduction
Unlike arrays, 2D arrays require nested iterative statements to traverse and access all elements. The easiest way to accomplish this is in row-major order. There may be some problems that use different algorithms so it is also important to consider additional traversal patterns, such as back and forth or column-major.
Because 2D arrays are traversed using nested loops, the number of times a code segment executes is multiplied. Recall that in a nested loop, the inner loop must complete all iterations before the outer loop can continue.
Printing a 2D Array
Nested iteration statements are used to traverse and access all elements in a 2D array. Since 2D arrays are stored as arrays of arrays, the way 2D arrays are traversed using for loops is like array objects. “Row-major order” refers to an ordering of 2D array elements where traversal occurs across each row, while “column-major order” traversal occurs down each column.
To print a 2D array, use a nested for loop. Consider the box 2d array from the previous lesson. This example shows a “row-major order”.
Nested iteration statements can also be written to traverse the 2D array in “column-major order”. This example shows a 2D array being initialized in column-major order.
If an enhanced for loop is used to traverse a 2D array, the variable must be the type of each row, which is an array. The inner loop traverses a single row. Therefore, the inner for-each loop variable must be the same type as the elements stored in the array.
This example will print the elements of the 2D array using a for-each loop.
Position Free Response Question
Click to download the Position Free Response Question. Links to an external site.
View the following Free Response Question Video below. Write your own solution on paper and then use the video to check your answer.
Position Free Response Question Video
ArrayTester Free Response Question
Click to download the ArrayTester Free Response Question. Links to an external site.
View the following Free Response Question Videos below. Write your own solution on paper and then use the video to check your answer.
ArrayTester Free Response Question Videos
Click on "Runestone Academy" below to open the required reading that is listed.
Runestone Academy: AP CSA – Java Review Links to an external site.:
READ: 10.7 – Looping through a 2D Array
READ 5 Steps to a 5:
- Concept 5
- Concept 6
2D Array Challenge
Practice-It! Practice
1. Go to the PracticeIt website Links to an external site..
2. Log into account.
3. Click on Start Practicing!
4. Go to the most recent edition.
5. Click on Chapter 7: Arrays
6. Complete Self-Checks: 7.31 – 7.35.
2D Arrays Test Review
- Go to AP Classroom Links to an external site..
- Complete Unit 8 Progress Check(s).
IMAGES CREATED BY GAVS