PrepGo

2D Array Traversals - AP Computer Science A Study Guide

Written by AP Content Team, Verified for 2026 AP Exams, Last updated: May 2026

Learn with study guides reviewed by top AP teachers. This guide takes about 10 minutes to read.

Getting Started

Two-dimensional (2D) arrays are fundamental for organizing data in a grid-like structure, such as a spreadsheet, a game board, or a pixelated image. To work with this data—to find a value, calculate a sum, or modify elements—we need a systematic way to visit every single cell in the grid. This process of visiting each element in a structured order is called a traversal.

What You Should Be Able to Do

  • Write nested for loops to visit every element in a 2D array.

  • Access and process individual elements using array[row][col] syntax inside a traversal.

  • Implement both row-major and column-major traversal patterns.

  • Trace the execution of a 2D array traversal, tracking the loop control variables and the element being accessed.

Key Concepts & Java Implementation

The Core Idea

A 2D array in Java is best understood as an "array of arrays." The outer array holds each of the rows, and each of those rows is itself a 1D array containing the column elements.

To traverse this structure, we cannot use a single loop. Instead, we use a nested loop:

  1. An outer loop iterates through the rows of the 2D array, from the first row (index 0) to the last.

  2. An inner loop iterates through the columns of the current row, from the first column (index 0) to the last.

By placing the column loop inside the row loop, we ensure that for each row selected by the outer loop, the inner loop visits every single column within it before the outer loop moves to the next row. This standard approach is called row-major order.

Syntax & Implementation

The key to a correct traversal is using the correct bounds for your loops.

  • The number of rows is given by arrayName.length.

  • The number of columns in a specific row r is given by arrayName[r].length.

Row-Major Traversal

This is the most common traversal pattern. It processes the grid one full row at a time.

Annotated Java Example: Printing All Elements

This code iterates through each row, and for each row, it iterates through each column, printing the element at [row][col].


// Assume 'grades' is a 2D array of integers

// int[][] grades = { {87, 92, 73}, {95, 89, 91}, {78, 82, 88}, {99, 94, 85} };


// Outer loop iterates through the rows

for (int row = 0; row < grades.length; row++) {

    // Inner loop iterates through the columns of the current row

    for (int col = 0; col < grades[row].length; col++) {

        // Access and print the element at the current row and column

        System.out.print(grades[row][col] + " "); 

    }

    // Move to the next line after printing all columns in a row

    System.out.println(); 

}

Output:


87 92 73 

95 89 91 

78 82 88 

99 94 85 

Column-Major Traversal

This pattern is less common but still important. It processes the grid one full column at a time. To achieve this, we reverse the loops: the outer loop iterates through columns, and the inner loop iterates through rows.

Important Note: This simple implementation assumes the 2D array is rectangular (all rows have the same number of columns).

Annotated Java Example: Column-Major Printing

This code iterates through each column index, and for each column, it iterates through each row to print the element.


// Assume 'grades' is the same rectangular 2D array as before.

// int[][] grades = { {87, 92, 73}, {95, 89, 91}, {78, 82, 88}, {99, 94, 85} };


// Outer loop iterates through the column indices

// We assume the array is rectangular, so we can use the length of the first row.

for (int col = 0; col < grades[0].length; col++) {

    // Inner loop iterates through the rows

    for (int row = 0; row < grades.length; row++) {

        // Access and print the element at the current row and column

        System.out.print(grades[row][col] + " ");

    }

    // Move to the next line after printing all elements in a column

    System.out.println();

}

Output:


87 95 78 99 

92 89 82 94 

73 91 88 85 

Tracing & Analysis

Let's trace a row-major traversal on a small 2D array to see how the variables change.

Code to Trace:


int[][] matrix = { {10, 20}, {30, 40} };

int sum = 0;

for (int r = 0; r < matrix.length; r++) {

    for (int c = 0; c < matrix[r].length; c++) {

        sum += matrix[r][c];

    }

}

Execution Trace:

Outer Loop (r)Inner Loop (c)matrix[r][c]sum (after update)
001010
012030
103060
1140100

Analysis:

For many algorithms, like finding the sum or average of all elements, the traversal order (row-major vs. column-major) does not change the final result. However, for algorithms that depend on the sequence of access, like printing the grid in its natural layout, the order is critical. Always use array[row].length for the inner loop's bound in a row-major traversal; this makes your code robust and able to handle non-rectangular ("jagged") arrays correctly.

Java Syntax Quick-Reference

A compact reference for the syntax used in 2D array traversals.

SyntaxPurpose
array.lengthWhen array is a 2D array, this returns the number of rows.
array[row].lengthReturns the number of columns (elements) in the specified row.
array[row][col]Accesses the element at the specified row and col index.
for (init; cond; i++)The standard for loop structure used for both outer and inner loops.

Core Code Examples & Terminology

  • Traversal: The process of systematically visiting, accessing, and/or processing each element in a data structure exactly once.

  • Nested Loop: A control flow structure where one loop is placed inside the body of another. The inner loop completes all its iterations for each single iteration of the outer loop.

  • Row-Major Order: A traversal method for a 2D array that processes all elements in the first row, then all elements in the second row, and so on.

  • Column-Major Order: A traversal method for a 2D array that processes all elements in the first column, then all elements in the second column, and so on.

  • Core Snippet 1: Standard Row-Major Traversal

    
    for (int r = 0; r < data.length; r++) {
    
        for (int c = 0; c < data[r].length; c++) {
    
            // Process data[r][c] here
    
        }
    
    }
    

    This nested loop structure is the canonical way to visit every element in a 2D array, one row at a time.

  • Core Snippet 2: Summing All Elements

    
    int total = 0;
    
    for (int r = 0; r < data.length; r++) {
    
        for (int c = 0; c < data[r].length; c++) {
    
            total += data[r][c];
    
        }
    
    }
    

    This demonstrates a common application of traversal: aggregating a value from all elements in the array.

Core Skill Check

  • Code Tracing: What is the final value of count after this Java code runs?

    int[][] arr = {{1, 0, 5}, {2, 3, 0}}; int count = 0; for(int r=0; r<arr.length; r++){ for(int c=0; c<arr[r].length; c++){ if(arr[r][c] == 0) { count++; } } }

    Answer: 2

  • Debugging: Identify the runtime error in this Java code, assuming grid is a 3x4 array.

    for (int r = 0; r <= grid.length; r++) { System.out.println(grid[r][0]); }

    Answer: ArrayIndexOutOfBoundsException. The loop condition r <= grid.length should be r < grid.length.

  • Application: Write a single line of Java code that gets the number of columns in the first row of a 2D array named board.

    Answer: int numCols = board[0].length;

Common Misconceptions & Errors

  1. Incorrect Loop Bounds: Using data.length (the number of rows) for both the outer and inner loop's condition. The inner loop must use data[r].length (the length of the current row).

  2. Off-by-One Errors: Using <= in a loop's condition (e.g., r <= data.length) will cause an ArrayIndexOutOfBoundsException because the largest valid index is data.length - 1.

  3. Swapped Indices: Writing data[col][row] when you mean data[row][col]. This can cause logic errors or exceptions if the array is not square.

  4. Assuming Rectangular Arrays: A column-major traversal that uses data[0].length as the bound for the outer (column) loop will fail if the array is "jagged" and a subsequent row is shorter than the first.

Summary

Traversing a 2D array is essential for processing grid-based data. The standard method uses a nested for loop, where the outer loop handles rows and the inner loop handles columns. This pattern, known as row-major order, is the most common and intuitive. Correctly using array.length to get the number of rows and array[row].length to get the number of columns in the current row is the key to writing bug-free traversal code. Mastering this pattern allows you to perform any operation on a 2D array, from simple calculations to complex data manipulation.