StudyFox

2D arrays and recursion

Open in StudyFox Free, no ads. Practice, track progress and quiz yourself in the app.

AP Computer Science A · Lesson 6 of 6 · 8 min read

2D arrays

int[][] grid = new int[3][4]; has 3 rows and 4 columns. grid.length is the number of rows; grid[0].length is the number of columns. Traverse with nested loops: row-major (outer loop over rows) or column-major.

int total = 0;
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[0].length; c++) {
        total += grid[r][c];
    }
}

Recursion

A recursive method calls itself. It needs a base case that stops the recursion and a recursive call that moves toward it.

public static int factorial(int n) {
    if (n <= 1) return 1;          // base case
    return n * factorial(n - 1);    // recursive call
}

Check your understanding

For int[][] g = new int[5][2]; what is g[0].length?

  1. 5
  2. 2
  3. 10
  4. 0
Show answer

Answer: B. g has 5 rows, and each row (like g[0]) has 2 columns.