Unit 4 Cycle 2 Day 10: 2D Array: Main Diagonal

Unit 4 Advanced (Cycle 2) Day 10 of 28 Advanced

2D Array: Main Diagonal

Section 4.11 — 2D Array Algorithms

Key Concept

The main diagonal of a 2D array consists of elements where the row index equals the column index: grid[0][0], grid[1][1], grid[2][2], etc. Accessing diagonal elements requires only a single loop: for (int i = 0; i < grid.length; i++) use grid[i][i]. The array must be square (or you must check bounds for rectangular arrays). The AP exam may ask about the secondary diagonal (grid[i][grid.length - 1 - i]) or both diagonals in the same problem.

Consider the following code segment.

int[][] grid = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int diagSum = 0; for (int i = 0; i < grid.length; i++) { diagSum += grid[i][i]; } System.out.println(diagSum);

What is printed?

Answer: (A) 15

Main diagonal: grid[0][0]=1, grid[1][1]=5, grid[2][2]=9. Sum = 15.

Why Not the Others?

(B) 12 does not correspond to any diagonal.

(C) 6 is just the first row sum.

(D) 45 is the sum of ALL elements.

Common Mistake

Main diagonal has row = column. Access with grid[i][i] in a single loop. Anti-diagonal: grid[i][n-1-i].

AP Exam Tip

Diagonal traversal uses a single loop, not nested loops. grid[i][i] for main diagonal.

Review this topic: Section 4.11 — 2D Array Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.