AP CSA Lesson 4.12: Traversing 2D Arrays

AP CSA • Unit 4: Data Collections • Lesson 4.12

Traversing 2D Arrays: Nested Loops

A 2D array is a grid of rows and columns. Reach a cell with grid[row][col], and visit every cell with a nested loop. Get the two lengths right and the rest is the patterns you already know.

Design Code Develop Code Analyze Code Document Code Use Computers Responsibly
Loading the interactive lesson. If this note stays visible, this preview is blocking JavaScript. Download the file and open it in a browser (Chrome), or view it on the live page, to use the editor, game, and quiz.
Learn
Practice
Assess
Scenario

The problem this code solves

A seating chart, a spreadsheet, a game board, the pixels of an image: all of them are grids, rows of columns, and the natural way to store one is a 2D array. To total a spreadsheet, find the brightest pixel, or check a winning line on a board, the program walks the grid cell by cell with a nested loop. This is the last big traversal pattern, and it is the one the exam always tests in free response.

Skill focus: today you Analyze code (predict what a nested traversal produces), Develop it (write the two loops with the right lengths), and Design it (choose row-major or column-major).
Learn

2D arrays: a grid of rows and columns

A 2D array is an array of arrays. You reach an element with two indices: grid[r][c], the value in row r, column c. Rows come first. Almost every 2D task is a nested loop: an outer loop over rows, an inner loop over the columns in that row.

The nested traversal

int[][] grid = {{1,2,3}, {4,5,6}};
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {
        System.out.print(grid[r][c]);
    }
}
The two lengths
grid.length number of rows
grid[r].length columns in row r
grid[r][c] row r, column c

grid.length is the row count. grid[r].length is the number of columns in that row. Mixing them up is the most common 2D bug.

Row-major vs column-major

// row-major: outer loop = rows
for (int r = 0; r < grid.length; r++)
  for (int c = 0; c < grid[r].length; c++)
    ... grid[r][c] ...

// column-major: outer loop = columns
for (int c = 0; c < grid[0].length; c++)
  for (int r = 0; r < grid.length; r++)
    ... grid[r][c] ...
Same cells, different order
row-major across each row, top to bottom
column-major down each column, left to right
Watch out: to visit every cell, the inner loop must use the correct length. Row-major inner bound is grid[r].length (columns). Column-major inner bound is grid.length (rows). Swapping them is how you get ArrayIndexOutOfBoundsException.
Watch out: a for-each also works. for (int[] row : grid) gives you each row array, then for (int x : row) gives each value. Clean for reading, but like any for-each it cannot change the elements.

Vocabulary

Term Meaning
2D array An array of arrays, addressed by two indices: grid[row][col].
Row One inner array. grid.length is the number of rows.
Column A position within a row. grid[r].length is the number of columns in row r.
Row-major Traversal where the outer loop is rows: across each row, top to bottom.
Column-major Traversal where the outer loop is columns: down each column, left to right.

Predict first, then check

1. int[][] g = {{1,2,3},{4,5,6}}; What is g.length?
2. For the same grid, what is g[0].length?
3. How many cells total does a 2-row, 3-column grid have?
See it in memory

See the row-major traversal

Row-major order walks across row 0 first, then row 1, summing as it goes. Play it and watch the pointer move left to right, top to bottom.

int sum = 0;
for (int r = 0; r < grid.length; r++) {
  for (int c = 0; c < grid[r].length; c++) {
    sum += grid[r][c];
  }
}
sum0
0
1
2
0
1
2
3
1
4
5
6
Original interactive 2D traversal. The pointer moves in row-major order; the running sum is on the left.
Practice • write and run real Java

Live code editor

Eight problems, six scaffolded and two open-ended. Write Java, press Run to execute it, and Check to test against the expected output. Hints and the solution are here if you need them, but using them is tracked, so try first.

Practice • fluency

Grid Walker Arcade

Six quick rounds on 2D arrays. Read the grid or the loop and type the result. Drills the nested-loop and length patterns the 2D array FRQ tests.

Assess • six questions at AP difficulty

Multiple choice

Predict your answer before reading the options. Watch for the qualifier words. After you answer, the rationale explains every distractor.

Assess • free-response connection

FRQ connection: the 2D array question

Every exam has a 2D array free-response question, and it is almost always a nested-loop traversal with a condition. Practice the core move: walk the grid and count what matches.

Every student challenged

Choose your lane

Support

  • Reread the Code and Memory panels
  • Editor problems 1 to 3 with hints on
  • Retry the quiz until 80%
  • Use the FRQ method shell

Core

  • All 8 editor problems
  • Full game run
  • The 6-question quiz once
  • The FRQ connection

Challenge

  • Open-ended problems 7 and 8 with no hints
  • Rewrite one loop a different way
  • Extend the FRQ
  • Lead a class trace
This lesson reports to the gradebook: lesson (completion), exercise-1 (code editor), exercise-2 (game), quiz (MCQ), and exercise-3 (FRQ). Live usage is tracked in window.LESSON_USAGE.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]