Problem 1
Row-Major Traversal Output
int[][] grid = {{1, 2, 3},
{4, 5, 6}};
for (int r = 0; r < grid.length; r++)
{
for (int c = 0; c < grid[0].length; c++)
{
System.out.print(grid[r][c] + " ");
}
}
Row-major: visits all columns in row 0 first (1 2 3), then all columns in row 1 (4 5 6).
Problem 2
Column-Major Traversal Output
int[][] grid = {{1, 2, 3},
{4, 5, 6}};
for (int c = 0; c < grid[0].length; c++)
{
for (int r = 0; r < grid.length; r++)
{
System.out.print(grid[r][c] + " ");
}
}
Column-major: visits all rows in column 0 (1 4), then all rows in column 1 (2 5), then column 2 (3 6).
Problem 3
Row Sum Accumulation
int[][] data = {{2, 4, 6},
{1, 3, 5},
{7, 8, 9}};
for (int r = 0; r < data.length; r++)
{
int rowSum = 0;
for (int c = 0; c < data[0].length; c++)
{
rowSum += data[r][c];
}
System.out.println("Row " + r + ": " + rowSum);
}
Row 0: 12
Row 1: 9
Row 2: 24
The accumulator
rowSum resets to 0 for each row. Row 0: 2+4+6=12. Row 1: 1+3+5=9. Row 2: 7+8+9=24.Problem 4
Diagonal Access
int[][] matrix = {{10, 20, 30},
{40, 50, 60},
{70, 80, 90}};
int sum = 0;
for (int i = 0; i < matrix.length; i++)
{
sum += matrix[i][i];
}
System.out.println(sum);
Main diagonal: matrix[0][0]=10, matrix[1][1]=50, matrix[2][2]=90. Sum = 10+50+90 = 150. This only works on square grids.
Problem 5
Modify Grid In Place
int[][] grid = {{1, 2},
{3, 4}};
for (int r = 0; r < grid.length; r++)
{
for (int c = 0; c < grid[0].length; c++)
{
grid[r][c] = grid[r][c] * (r + c);
}
}
// What is grid now?
grid[0][0] = 1*(0+0) = 0. grid[0][1] = 2*(0+1) = 2. grid[1][0] = 3*(1+0) = 3. grid[1][1] = 4*(1+1) = 8.
Crush Every 2D Array Problem
Get structured daily practice with the Cram Kit or work 1-on-1 with an expert.
Get the Cram Kit — $29.99 Book Tutoring