Teacher Guide: 2D Arrays

Student page: 2D Arrays IB Syllabus: B2.2.2 Estimated periods: 2 (90 min each) Prerequisites: 1D Arrays, Iteration

Contents

  1. Lesson Plans
  2. Differentiation
  3. Answer Keys
  4. Integration Notes
    1. Additional Resources

Lesson Plans

Period 1: Declaration, Traversal, Basic Operations

Phase Time Activity Student Page Section
Warm-up 10 min Draw 3x4 grid on board, label rows 0-2 / cols 0-3. “How many elements? What is [1][2]?”
Teach 25 min Declaration, nested loop traversal (outer=row, inner=col), accessing elements Key Concepts
Practice 40 min Core #1-2 (Multiplication Table, Find the Largest) Practice Exercises
Wrap-up 15 min Quick Code Check MCQs Quick Code Check

Teaching notes:

  • Visual first: always draw the grid before code
  • Real-world contexts: grade book (students x assignments), game board, seating chart
  • Standard traversal: outer loop = rows (matrix.length), inner loop = cols (matrix[row].length)
  • Ask: “What if you swapped the loops?” — column-first traversal, not wrong but non-standard

Additional activities:

  • Live coding: 2D char array example (letter grid or word search)
  • Seating plan exercise: model a classroom as a 2D array of student names
  • Discussion prompt: “Where do you see 2D structures in real life?” (calendars, spreadsheets, game boards)
  • Common trap: row vs column index confusion — always [row][col], never [col][row]

Period 2: Row/Column Operations, Matrix Operations

Phase Time Activity Student Page Section
Warm-up 10 min “How would you calculate each student’s average grade?” — describe algorithm
Teach 20 min Row sums/averages, column sums, transpose concept, matrix addition Worked Examples
Practice 45 min Core #3, Extension #4-5, Challenge #6 Practice Exercises
Wrap-up 15 min Trace exercise + connect to file I/O (reading CSV into 2D array) Trace Exercise

Additional activities:

  • Population migration exercise: track movement between regions using a 2D array
  • Discuss row vs column index confusion — the most common 2D array bug

Differentiation

Supporting weaker students:

Strategy When to use Example
Grid worksheet Can’t visualize 2D indexing Print blank grid with row/col labels — fill in values by hand
1D first, then 2D Overwhelmed by nested loops “Do it for one row first, then wrap in outer loop”
Traversal template Can’t write nested loops Provide: for (int r = 0; r < matrix.length; r++) { for (int c = 0; c < matrix[r].length; c++) { /* use matrix[r][c] */ } }
Pair programming During Core exercises One student handles outer loop, partner handles inner

Extending stronger students:

Strategy When to use Example
Population Migration Finishes Core early 2D array tracking migration between regions
Challenge #6 Extended learners Tic-tac-toe board with win detection
Diagonal operations After matrix basics “Sum the main diagonal of a square matrix”
Jagged arrays After transpose “What if each row has a different number of columns?”
Seating plan After Core #1 Model a classroom seating chart with names in a 2D String array

Answer Keys

Core 1: Multiplication Table
public class MultiplicationTable {
    public static void main(String[] args) {
        int[][] table = new int[5][5];
        // Fill the table
        for (int r = 0; r < table.length; r++) {
            for (int c = 0; c < table[r].length; c++) {
                table[r][c] = (r + 1) * (c + 1);
            }
        }
        // Print the table
        for (int r = 0; r < table.length; r++) {
            for (int c = 0; c < table[r].length; c++) {
                System.out.print(table[r][c] + "\t");
            }
            System.out.println();
        }
    }
}

Expected output:

1	2	3	4	5
2	4	6	8	10
3	6	9	12	15
4	8	12	16	20
5	10	15	20	25

Common mistakes: Using r * c instead of (r+1) * (c+1) (first row/col would be all zeros); forgetting println() after inner loop.

Marking notes: Must use nested loops for both filling and printing. The \t tab formatting is preferred but spaces are acceptable.

Core 2: Find the Largest
public class FindLargest {
    public static void main(String[] args) {
        int[][] data = { {3, 7, 2}, {9, 1, 5}, {4, 8, 6} };
        int max = data[0][0];
        int maxRow = 0;
        int maxCol = 0;
        for (int r = 0; r < data.length; r++) {
            for (int c = 0; c < data[r].length; c++) {
                if (data[r][c] > max) {
                    max = data[r][c];
                    maxRow = r;
                    maxCol = c;
                }
            }
        }
        System.out.println("Largest: " + max + " at [" + maxRow + "][" + maxCol + "]");
    }
}

Expected output: Largest: 9 at [1][0]

Common mistakes: Initializing max to 0 instead of data[0][0]; not tracking both row AND column position; using <= in loop bounds.

Marking notes: Must track position (row and col). Seed with data[0][0]. Key trap: don’t initialize max to 0.

Core 3: Row Averages
public class RowAverages {
    public static void main(String[] args) {
        int[][] grades = {
            {85, 90, 78, 92},
            {70, 65, 88, 75},
            {95, 88, 92, 97}
        };
        for (int r = 0; r < grades.length; r++) {
            int sum = 0;
            for (int c = 0; c < grades[r].length; c++) {
                sum += grades[r][c];
            }
            double avg = (double) sum / grades[r].length;
            System.out.println("Student " + (r + 1) + " average: " + avg);
        }
    }
}

Expected output:

Student 1 average: 86.25
Student 2 average: 74.5
Student 3 average: 93.0

Common mistakes: Integer division (sum / grades[r].length without cast); using outer array length for column count; resetting sum outside the outer loop.

Marking notes: Must cast to double for average. Must use grades[r].length for number of columns (not hardcoded). Sum must be reset each row.

Extension 4: Transpose
public class Transpose {
    public static void main(String[] args) {
        int[][] original = {
            {1, 2, 3, 4},
            {5, 6, 7, 8}
        };
        // Transpose: rows become columns
        int[][] transposed = new int[original[0].length][original.length];
        for (int r = 0; r < original.length; r++) {
            for (int c = 0; c < original[r].length; c++) {
                transposed[c][r] = original[r][c];
            }
        }
        // Print original
        System.out.println("Original (2x4):");
        for (int r = 0; r < original.length; r++) {
            for (int c = 0; c < original[r].length; c++) {
                System.out.print(original[r][c] + "\t");
            }
            System.out.println();
        }
        // Print transposed
        System.out.println("Transposed (4x2):");
        for (int r = 0; r < transposed.length; r++) {
            for (int c = 0; c < transposed[r].length; c++) {
                System.out.print(transposed[r][c] + "\t");
            }
            System.out.println();
        }
    }
}

Expected output:

Original (2x4):
1	2	3	4
5	6	7	8
Transposed (4x2):
1	5
2	6
3	7
4	8

Common mistakes: Wrong dimensions for transposed array (new int[original.length][original[0].length] — that’s the same size); swapping r and c wrong in the assignment.

Marking notes: Key insight: transposed[c][r] = original[r][c]. New dimensions: rows = original cols, cols = original rows.

Extension 5: Matrix Addition
public class MatrixAddition {
    public static void main(String[] args) {
        int[][] a = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
        int[][] b = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };
        int[][] result = new int[3][3];
        for (int r = 0; r < 3; r++) {
            for (int c = 0; c < 3; c++) {
                result[r][c] = a[r][c] + b[r][c];
            }
        }
        // Print all three
        System.out.println("Matrix A:");
        for (int r = 0; r < 3; r++) {
            for (int c = 0; c < 3; c++) {
                System.out.print(a[r][c] + "\t");
            }
            System.out.println();
        }
        System.out.println("Matrix B:");
        for (int r = 0; r < 3; r++) {
            for (int c = 0; c < 3; c++) {
                System.out.print(b[r][c] + "\t");
            }
            System.out.println();
        }
        System.out.println("Result (A + B):");
        for (int r = 0; r < 3; r++) {
            for (int c = 0; c < 3; c++) {
                System.out.print(result[r][c] + "\t");
            }
            System.out.println();
        }
    }
}

Expected: Each element in result is 10 (1+9, 2+8, etc.)

Common mistakes: Using matrix multiplication formula instead of element-wise addition; wrong loop bounds.

Marking notes: Must print all three matrices. Element-wise: result[r][c] = a[r][c] + b[r][c]. Accept using .length instead of hardcoded 3.

Challenge 6: Tic-Tac-Toe Board
public class TicTacToe {
    public static void main(String[] args) {
        char[][] board = new char[3][3];
        // Initialize all cells to '-'
        for (int r = 0; r < board.length; r++) {
            for (int c = 0; c < board[r].length; c++) {
                board[r][c] = '-';
            }
        }
        // Place some moves
        board[0][0] = 'X';
        board[0][1] = 'X';
        board[0][2] = 'X';
        board[1][0] = 'O';
        board[1][1] = 'O';
        board[2][2] = 'O';
        // Print the board
        for (int r = 0; r < board.length; r++) {
            for (int c = 0; c < board[r].length; c++) {
                System.out.print(board[r][c]);
                if (c < board[r].length - 1) {
                    System.out.print(" | ");
                }
            }
            System.out.println();
        }
        // Check each row for a win
        for (int r = 0; r < board.length; r++) {
            if (board[r][0] != '-' && board[r][0] == board[r][1] && board[r][1] == board[r][2]) {
                System.out.println("Row " + r + " wins for " + board[r][0] + "!");
            }
        }
    }
}

Expected output:

X | X | X
O | O | -
- | - | O
Row 0 wins for X!

Common mistakes: Not checking for non-empty (!= '-') before checking equality (empty row would “win”); using .equals() for char comparison (chars use ==); wrong separator placement.

Marking notes: Must initialize to ‘-‘, must print with separators, must check row win. Column and diagonal win checks are bonus (not required by the exercise). Char comparison uses == (not .equals() — chars are primitives).


Integration Notes

Item In Class Homework Link
Worked Examples Walk through together Worked Examples
Quick Code Check End of Period 1 Quick Code Check
Core #1-2 Period 1 practice Practice Exercises
Core #3, Extension #4-5 Period 2 practice Complete for homework Practice Exercises
Challenge #6 Optional extension Practice Exercises
Trace Exercise Period 2 wrap-up Trace Exercise
GitHub Classroom Due end of week GitHub Classroom

Additional Resources

  • Grid worksheet (printable blank grids with row/col labels for hand-tracing)
  • 2D char array live coding example (letter grid or word search)
  • Population migration practical (extended project)

Back to top

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

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