AP Computer Science A Unit 8 Review

AP Computer Science A Unit 8 Review with Java Coding

1. 2D Arrays

2D arrays are data structures that resemble a table arranged with rows and columns. To access each cell, two indices are used: one specifies the row and the other specifies the column.

public class TwoDArrayExample {
    public static void main(String[] args) {
        // Creating a 2D array
        int[][] matrix = new int[3][3];
        
        // Initializing the 2D array
        matrix[0][0] = 1;
        matrix[0][1] = 2;
        matrix[0][2] = 3;
        matrix[1][0] = 4;
        matrix[1][1] = 5;
        matrix[1][2] = 6;
        matrix[2][0] = 7;
        matrix[2][1] = 8;
        matrix[2][2] = 9;
        
        // Accessing elements of the 2D array
        System.out.println("Element at (1, 1): " + matrix[1][1]); // Output: 5
    }
}

2. Traversing 2D Arrays

To traverse 2D arrays, nested for loops are used. The outer loop represents the rows, and the inner loop represents the columns.

public class TwoDArrayTraversalExample {
    public static void main(String[] args) {
        // Creating and initializing a 2D array
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        
        // Traversing the 2D array
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

These examples cover the topics of Unit 8 and demonstrate how to create, access, and traverse 2D arrays.