Even-sized matrix
When n is even, no cell sits on both diagonals. The sum is simply the sum of both diagonals — no correction needed.
An LED display panel uses a square grid of pixels. A quick diagnostic check lights up both diagonals — primary (top-left to bottom-right) and secondary (top-right to bottom-left) — and measures their combined brightness. A single indexed loop walks both diagonals simultaneously, accumulating the sum. When the grid has odd dimensions, the center pixel sits on both diagonals and must be counted only once.
The primary diagonal visits matrix[r][r] — the row and column indices always match. The secondary diagonal visits matrix[r][n − 1 − r] — the column counts down as the row counts up. In an odd-sized matrix both diagonals cross at the center cell matrix[n/2][n/2], which would be double-counted if left uncorrected.
Both diagonals are walked in a single loop. The primary diagonal has col = row; the secondary has col = n − 1 − row.
For each row r, add matrix[r][r] to the sum.
For each row r, add matrix[r][n − 1 − r] to the sum.
When n is odd, the center element sits on both diagonals. Subtract it once to correct the double count.
Understanding boundary behavior is as important as the main algorithm path.
When n is even, no cell sits on both diagonals. The sum is simply the sum of both diagonals — no correction needed.
A single cell is both diagonals and the center. The answer is that single value.
Time: O(n) — one pass over the rows.
Space: O(1) — only a running sum.