Unit 4 Cycle 2 Day 10: 2D Array: Main Diagonal
Share
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.
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.