2D Arrays
IB Syllabus: B2.2.2 — Describe the characteristics of a 2D array. Construct algorithms using 2D arrays.
Table of Contents
- Key Concepts
- Worked Examples
- Quick Code Check
- Trace Exercise
- Code Completion
- Spot the Bug
- Output Prediction
- Practice Exercises
- GitHub Classroom
- Connections
Key Concepts
A 2D array is an array of arrays — a table with rows and columns. Think of a spreadsheet, a game board, or a grade book.
Declaration
// Declare with size: 3 rows, 4 columns
int[][] grid = new int[3][4];
All elements default to 0 (for int), false (for boolean), or null (for objects).
Initialisation with Values
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing Elements
// Access: matrix[row][col] — row first, column second
System.out.println(matrix[1][2]); // 6 (row 1, column 2)
matrix[0][1] = 99; // modify an element
A common mistake is swapping row and column:
matrix[col][row]instead ofmatrix[row][col]. Always think row first, column second.
Dimensions
int rows = matrix.length; // number of rows (3)
int cols = matrix[0].length; // number of columns in row 0 (3)
Visual Layout
col 0 col 1 col 2
┌───────┬───────┬───────┐
row 0 │ 1 │ 2 │ 3 │
├───────┼───────┼───────┤
row 1 │ 4 │ 5 │ 6 │
├───────┼───────┼───────┤
row 2 │ 7 │ 8 │ 9 │
└───────┴───────┴───────┘
matrix[1][2] = 6 (row 1, col 2)
matrix.length = 3 (rows)
matrix[0].length = 3 (cols)
Worked Examples
Example 1: Print a Grid
The fundamental pattern — nested loops to visit every element.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Outer loop: each row
for (int row = 0; row < matrix.length; row++) {
// Inner loop: each column in this row
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + "\t");
}
System.out.println(); // new line after each row
}
Output:
1 2 3
4 5 6
7 8 9
The outer loop iterates over rows. For each row, the inner loop iterates over columns. \t adds a tab between values for neat alignment.
Example 2: Row Sum
Calculate the sum of a single row.
int[][] grades = {
{85, 92, 78},
{90, 88, 95},
{70, 65, 80}
};
int targetRow = 1;
int sum = 0;
for (int col = 0; col < grades[targetRow].length; col++) {
sum = sum + grades[targetRow][col];
}
System.out.println("Row " + targetRow + " sum: " + sum); // Row 1 sum: 273
Notice: only one loop is needed because we fix the row and iterate over columns.
Example 3: Search in a 2D Array
Find whether a target value exists anywhere in the grid.
int[][] data = {
{12, 45, 67},
{89, 23, 56},
{34, 78, 90}
};
int target = 23;
boolean found = false;
for (int row = 0; row < data.length && !found; row++) {
for (int col = 0; col < data[row].length && !found; col++) {
if (data[row][col] == target) {
found = true;
System.out.println("Found " + target + " at [" + row + "][" + col + "]");
}
}
}
if (!found) {
System.out.println(target + " not found.");
}
Output: Found 23 at [1][1]
The && !found condition provides an early exit — no point continuing once the value is found.
Example 4: Transpose
Swapping rows and columns into a new array.
int[][] original = {
{1, 2, 3},
{4, 5, 6}
};
// Transpose: rows become columns and columns become rows
int[][] transposed = new int[original[0].length][original.length];
for (int row = 0; row < original.length; row++) {
for (int col = 0; col < original[row].length; col++) {
transposed[col][row] = original[row][col];
}
}
// Print transposed (3 rows, 2 cols)
for (int row = 0; row < transposed.length; row++) {
for (int col = 0; col < transposed[row].length; col++) {
System.out.print(transposed[row][col] + "\t");
}
System.out.println();
}
Output:
1 4
2 5
3 6
The key line is transposed[col][row] = original[row][col] — each element’s row and column indices are swapped.
Quick Code Check
Q1. Given int[][] matrix = new int[3][4], what does matrix.length return?
Q2. For a int[3][4] array, which access is valid?
Q3. What does this code print?
int[][] m = { {1,2,3}, {4,5,6}, {7,8,9} };
for (int r = 0; r < m.length; r++) {
for (int c = 0; c < m[r].length; c++) {
System.out.print(m[r][c] + " ");
}
System.out.println();
} Q4. Which of these is a common error when accessing 2D arrays?
Q5. Given int[][] matrix = new int[5][3], what is matrix[0].length?
Trace Exercise
Trace this nested loop over a 3x3 matrix. Fill in the value of matrix[row][col] and the running sum at each step.
int[][] matrix = {
{2, 4, 6},
{1, 3, 5},
{8, 7, 9}
};
int sum = 0;
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
sum = sum + matrix[row][col];
}
}
System.out.println("Total: " + sum);
| row | col | matrix[row][col] | sum |
|---|---|---|---|
| 0 | 0 | ||
| 0 | 1 | ||
| 0 | 2 | ||
| 1 | 0 | ||
| 1 | 1 | ||
| 1 | 2 | ||
| 2 | 0 | ||
| 2 | 1 | ||
| 2 | 2 |
Final output: Total:
Code Completion
Complete the method that calculates the sum of a specific column in a 2D array.
Unlike a row sum (which fixes the row and loops over columns), a column sum fixes the column and loops over each row. Fill in the blanks to complete the column sum calculation:
int[][] grades = {
{85, 92, 78},
{90, 88, 95},
{70, 65, 80}
};
int targetCol = 1;
int sum = 0;
for (int row = 0; row < ; row++) {
sum = sum + ;
}
System.out.println("Column " + targetCol + " sum: " + );
Spot the Bug
This code is supposed to sum all elements of a 2D array using nested loops, but it crashes with an ArrayIndexOutOfBoundsException. The bug is a classic off-by-one error in the loop boundary. Click the buggy line, then pick the fix.
Pick the correct fix:
Output Prediction
This code uses nested loops to traverse a 2D array row by row, printing each element followed by a space and starting a new line after each row. What is the exact output of this code?
int[][] arr = { {10, 20, 30}, {40, 50, 60} };
for (int r = 0; r < arr.length; r++) {
for (int c = 0; c < arr[r].length; c++) {
System.out.print(arr[r][c] + " ");
}
System.out.println();
}Type your answer (use \n to indicate a new line):
Pay close attention to spaces and newlines in output prediction questions. The
printlndoes.
Practice Exercises
Core
-
Multiplication Table — Write code in
mainthat creates a 5x5int[][]wheretable[r][c] = (r+1) * (c+1). Print the result as a formatted grid. -
Find the Largest — Given
int[][] data = { {3,7,2}, {9,1,5}, {4,8,6} }, write code to find and print the largest value and its position[row][col]. -
Row Averages — Given a 2D array of student grades (rows = students, columns = assignments), calculate and print each student’s average grade.
Extension
-
Transpose — Write code that transposes a 2x4 array into a 4x2 array. Print both the original and transposed arrays.
-
Matrix Addition — Given two 3x3 arrays
aandb, create a new arrayresultwhereresult[r][c] = a[r][c] + b[r][c]. Print all three matrices.
Challenge
- Tic-Tac-Toe Board — Create a
char[3][3]array representing a tic-tac-toe board. Write code that:- Initialises all cells to
'-' - Places some
'X'and'O'values - Prints the board with
|separators between columns - Checks whether a given row contains three of the same non-empty character (a win)
- Initialises all cells to
GitHub Classroom
Codespace Setup Instructions (click to expand)
First Time Setup
- Click “Open in GitHub” above, then click the green “Accept this assignment” button
- Wait for your repository to be created, then click “Open in Codespace”
- Wait for the Codespace to finish loading (you’ll see VS Code in your browser)
Important: Switch to Standard Mode
- Look at the bottom status bar — if it says
Java: Lightweight Mode, click on it and select Standard - Wait for Java to finish loading (status bar will say
Java: Ready) - Without Standard Mode, the Run button won’t work and you’ll get “Main method not found” errors
Dismiss Popups
You’ll see two notification popups — dismiss them both:
- “Would you like VS Code to periodically run git fetch?” → Click No
- “There’s a pull request associated with main” → Click Don’t Show Again
These are housekeeping popups, not part of the assignment.
How to Code
- Open
src/TwoDArrays.java— this is the only file you need to edit - Complete each
// TODOsection using nestedforloops - Click the Run button (▶ above
main) to test your output - Compare your output with the expected output written in the comments
How to Submit
- Click the Source Control icon (branch icon) in the left sidebar
- Type a message like
completed tasksin the message box - Click the green Commit button
- If asked “stage all changes?” → click Always
- Click Sync Changes → if asked about push/pull → click OK, Don’t Show Again
- Done — your teacher can see your results in the GitHub Classroom dashboard
Connections
- Prerequisites: 1D Arrays, Iteration
- Related: Linear Search (search patterns apply to 2D)
- Next: ArrayList (coming soon as sub-page)
- Forward: File I/O (reading CSV data into 2D arrays), OOP (arrays of objects)