2D Arrays

IB Syllabus: B2.2.2 — Describe the characteristics of a 2D array. Construct algorithms using 2D arrays.

Table of Contents

  1. Key Concepts
    1. Declaration
    2. Initialisation with Values
    3. Accessing Elements
    4. Dimensions
    5. Visual Layout
  2. Worked Examples
    1. Example 1: Print a Grid
    2. Example 2: Row Sum
    3. Example 3: Search in a 2D Array
    4. Example 4: Transpose
  3. Quick Code Check
  4. Trace Exercise
  5. Code Completion
  6. Spot the Bug
  7. Output Prediction
  8. Practice Exercises
    1. Core
    2. Extension
    3. Challenge
  9. GitHub Classroom
    1. First Time Setup
    2. Important: Switch to Standard Mode
    3. Dismiss Popups
    4. How to Code
    5. How to Submit
  10. 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 of matrix[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);
rowcolmatrix[row][col]sum
00
01
02
10
11
12
20
21
22

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.

1int[][] matrix = { {1,2}, {3,4}, {5,6} }; 2 3int sum = 0; 4for (int row = 0; row <= matrix.length; row++) { 5 for (int col = 0; col < matrix[row].length; col++) { 6 sum = sum + matrix[row][col]; 7 } 8} 9System.out.println("Sum: " + sum);

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 print method does not add a newline, while println does.


Practice Exercises

Core

  1. Multiplication Table — Write code in main that creates a 5x5 int[][] where table[r][c] = (r+1) * (c+1). Print the result as a formatted grid.

  2. 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].

  3. Row Averages — Given a 2D array of student grades (rows = students, columns = assignments), calculate and print each student’s average grade.

Extension

  1. Transpose — Write code that transposes a 2x4 array into a 4x2 array. Print both the original and transposed arrays.

  2. Matrix Addition — Given two 3x3 arrays a and b, create a new array result where result[r][c] = a[r][c] + b[r][c]. Print all three matrices.

Challenge

  1. 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)

GitHub Classroom

2D Arrays Practice
Practice nested loops with a grade table: print the grid, calculate row totals, column averages, find the highest grade, and search for a value. Includes a Population Migration challenge exercise.
Codespace Setup Instructions (click to expand)

First Time Setup

  1. Click “Open in GitHub” above, then click the green “Accept this assignment” button
  2. Wait for your repository to be created, then click “Open in Codespace”
  3. Wait for the Codespace to finish loading (you’ll see VS Code in your browser)

Important: Switch to Standard Mode

  1. Look at the bottom status bar — if it says Java: Lightweight Mode, click on it and select Standard
  2. Wait for Java to finish loading (status bar will say Java: Ready)
  3. 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

  1. Open src/TwoDArrays.java — this is the only file you need to edit
  2. Complete each // TODO section using nested for loops
  3. Click the Run button (▶ above main) to test your output
  4. Compare your output with the expected output written in the comments

How to Submit

  1. Click the Source Control icon (branch icon) in the left sidebar
  2. Type a message like completed tasks in the message box
  3. Click the green Commit button
  4. If asked “stage all changes?” → click Always
  5. Click Sync Changes → if asked about push/pull → click OK, Don’t Show Again
  6. 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)

Back to top

© EduCS.me — A resource hub for IB Computer Science

This site uses Just the Docs, a documentation theme for Jekyll.