Unit 8: 2D Array

AP Computer Science A: 51 practice questions with detailed explanations.

Unit Study Guide

Executive Summary

A 2D array is an array of arrays — a grid of rows, each row its own 1D array.

Creation and dimensions

int[][] grid = new int[rows][cols] makes a rectangle. grid.length is the number of rows; grid[r].length is the number of columns in row r. Access elements as grid[r][c] — row first, column second.

Traversals

Row-major order: outer loop over rows, inner over columns. Column-major swaps them. The inner condition should use grid[r].length so ragged arrays work. Enhanced for yields whole rows: for (int[] row : grid).

Algorithms

Sum or count with nested loops and an accumulator. Find max by comparing every element. Diagonal elements have r == c in a square grid; one loop suffices to sum them. Doubling every element needs indexed assignment — enhanced for cannot write.

Ragged arrays

Rows can have different lengths. Always read grid[r].length inside the loop rather than grid[0].length when rows may differ.

Exam traps

grid.length counts rows, not total elements. grid[r][c] vs grid[c][r] transposes the grid. Accessing grid[rows][0] or grid[0][cols] throws ArrayIndexOutOfBoundsException.

Top 5 Concepts to Master

  1. 1Read and write rows and columns correctly.
  2. 2Trace nested row-major and column-major loops.
  3. 3Implement 2D sum, count, and max.
  4. 4Handle ragged arrays safely.

Key Terms & Definitions

Practice with Flashcards
2D array

Array whose elements are arrays (rows).

Row-major order

Traversal completing each row in turn.

Column-major order

Traversal completing each column in turn.

Ragged array

2D array whose rows differ in length.

grid.length

Number of rows.

grid[r].length

Number of columns in row r.

Common Misconceptions: Exam Traps

grid.length is the total number of elements.

Correct: It is the number of rows.

grid[0].length works for every grid.

Correct: Ragged grids need grid[r].length per row.

Enhanced for can set 2D elements.

Correct: For-each copies values; indexed loops are needed.

grid[c][r] and grid[r][c] are interchangeable.

Correct: The order matters: row then column.

Question Bank Breakdown

By difficulty

easy 21medium 30

By topic

2D Array Creation 262D Array Algorithms 9Traversing 2D Arrays 9Row-Major vs Column-Major 7

All Questions in this Unit