- What the main diagonal of a matrix is — and why it only needs one loop
- How to compute the sum of the main diagonal (the trace)
- How to compute the sum of the anti-diagonal, the mirror-image
- Why the diagonal indices are
(i, i)— one increment per step - Why the middle cell is counted once even if you sum both diagonals
What the main diagonal is
The main diagonal of a matrix is the set of cells where the row index equals the column index: (0, 0), (1, 1), (2, 2), ..., (n-1, n-1). These cells run from the top-left corner down to the bottom-right corner, forming the "spine" of the matrix. For a 3×3 matrix, the diagonal has three cells. For an n×n matrix, it has n cells.
Summing the main diagonal gives what mathematicians call the trace of the matrix. It's a fundamental property — the trace equals the sum of the eigenvalues of the matrix (for diagonalizable matrices), and it's invariant under cyclic permutation of matrix products (trace(AB) = trace(BA)). It shows up in physics (the trace of the stress tensor is related to pressure), in computer graphics (the trace of a rotation matrix encodes the rotation angle), and in machine learning (the trace appears in the gradient of the log-determinant of a covariance matrix).
The anti-diagonal (also called the secondary diagonal or counter-diagonal) is the mirror image: cells where row index + column index equals n-1. For a 3×3 matrix, that's (0, 2), (1, 1), (2, 0). It runs from the top-right corner down to the bottom-left corner. Its sum is sometimes called the anti-trace, and it appears in checks for "anti-symmetric" or "persymmetric" matrices.
Both diagonals are easy to compute. The main diagonal cells are at index (i, i), so a single loop over i suffices. The anti-diagonal cells are at (i, n-1-i), so a single loop over i (with a computed column index) suffices. No nested loops needed — this is one of the few matrix operations that's O(n) instead of O(n²).
💡 In one line: for the main diagonal, sum a[i][i] for i from 0 to N-1. For the anti-diagonal, sum a[i][N-1-i] for the same range. Both are single loops — n iterations, not n².
Designing the diagonal-sum function
Two small functions, each with one loop:
| Part | Choice | Why |
|---|---|---|
| Function names | mainDiagonalSum and antiDiagonalSum | Distinguish the two diagonals clearly. Alternatives: trace and antiTrace. |
| Parameter | const int a[N][N] | Read-only. Square matrix only — the diagonal doesn't have a well-defined meaning for non-square matrices. |
| Return type | long long | The sum of N values might overflow int for large N. long long is safer. |
The prototypes:
#define N 3
long long mainDiagonalSum(const int a[N][N]);
long long antiDiagonalSum(const int a[N][N]);
And the definitions — each is three lines of logic:
long long mainDiagonalSum(const int a[N][N]) {
long long sum = 0;
for (int i = 0; i < N; i++) {
sum += a[i][i];
}
return sum;
}
long long antiDiagonalSum(const int a[N][N]) {
long long sum = 0;
for (int i = 0; i < N; i++) {
sum += a[i][N - 1 - i];
}
return sum;
}
The main diagonal uses a[i][i] — same index for row and column. The anti-diagonal uses a[i][N - 1 - i] — the column index counts down as the row index counts up. Both are single loops, and both run in O(n) time.
Here's a version that computes both diagonals in one pass — useful when you need both:
void bothDiagonals(const int a[N][N], long long *outMain, long long *outAnti) {
long long main_sum = 0;
long long anti_sum = 0;
for (int i = 0; i < N; i++) {
main_sum += a[i][i];
anti_sum += a[i][N - 1 - i];
}
*outMain = main_sum;
*outAnti = anti_sum;
}
Same loop, two accumulators, two results — one pass through the matrix. For a 1000×1000 matrix, this does 1000 iterations instead of 2000 (two separate calls). The gain is small here since the diagonal is O(n) not O(n²), but the pattern generalizes — for other matrix operations where you compute both diagonals inside a larger loop, this single-pass approach matters.
And a version that sums both diagonals together without double-counting the center cell of odd-sized matrices:
long long combinedDiagonalSum(const int a[N][N]) {
long long sum = 0;
for (int i = 0; i < N; i++) {
sum += a[i][i]; /* main diagonal */
sum += a[i][N - 1 - i]; /* anti-diagonal */
}
/* For odd N, the center cell is counted twice — subtract it once */
if (N % 2 == 1) {
sum -= a[N / 2][N / 2];
}
return sum;
}
This is a common trick when a problem asks for the sum of "both diagonals" — you add every cell from both diagonals, then correct for the center cell of odd-sized matrices (which is on both diagonals, so it's been counted twice). The correction is one subtraction, much cheaper than a second loop.
🎯 Key idea: the diagonal is a 1D slice of a 2D matrix, so it needs a 1D loop. The main diagonal is a[i][i]; the anti-diagonal is a[i][N-1-i]. Both are O(n), and both fit into the same pattern: initialize a sum, walk the diagonal, return.
Complete C Program
Program: read a square matrix, compute both diagonal sums
#include <stdio.h>
#define N 3
/* Function prototypes */
long long mainDiagonalSum(const int a[N][N]);
long long antiDiagonalSum(const int a[N][N]);
int main(void) {
int A[N][N];
printf("Enter matrix A (%d rows, %d columns):\n", N, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (scanf("%d", &A[i][j]) != 1) return 1;
}
}
printf("\nMatrix A:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) printf("%4d", A[i][j]);
printf("\n");
}
printf("\nMain diagonal sum: %lld\n", mainDiagonalSum(A));
printf("Anti-diagonal sum: %lld\n", antiDiagonalSum(A));
return 0;
}
/* Sum of the main diagonal: a[i][i] */
long long mainDiagonalSum(const int a[N][N]) {
long long sum = 0;
for (int i = 0; i < N; i++) {
sum += a[i][i];
}
return sum;
}
/* Sum of the anti-diagonal: a[i][N-1-i] */
long long antiDiagonalSum(const int a[N][N]) {
long long sum = 0;
for (int i = 0; i < N; i++) {
sum += a[i][N - 1 - i];
}
return sum;
}
And a version that shows both diagonals in a single pass through the matrix:
Variant: both diagonals in one pass
#include <stdio.h>
#define N 4
void diagonalsSum(const int a[N][N], long long *mainSum, long long *antiSum) {
*mainSum = 0;
*antiSum = 0;
for (int i = 0; i < N; i++) {
*mainSum += a[i][i];
*antiSum += a[i][N - 1 - i];
}
}
int main(void) {
int A[N][N] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
long long m, a;
diagonalsSum(A, &m, &a);
printf("Main: %lld\n", m);
printf("Anti: %lld\n", a);
return 0;
}
For this 4×4 matrix, the main diagonal is 1 + 6 + 11 + 16 = 34, and the anti-diagonal is 4 + 7 + 10 + 13 = 34. Both happen to equal 34 — a coincidence here, but a pleasing one. Note the anti-diagonal sum uses N - 1 - i, which for i=0 gives column 3 (value 4), for i=1 gives column 2 (value 7), and so on.
And the combined-sum version with the odd-N correction:
Variant: combined sum with double-count correction
#include <stdio.h>
#define N 3
long long combinedSum(const int a[N][N]) {
long long sum = 0;
for (int i = 0; i < N; i++) {
sum += a[i][i];
sum += a[i][N - 1 - i];
}
if (N % 2 == 1) {
sum -= a[N / 2][N / 2];
}
return sum;
}
int main(void) {
int A[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printf("Combined diagonal sum: %lld\n", combinedSum(A));
return 0;
}
For this 3×3 matrix, the main diagonal is 1 + 5 + 9 = 15, and the anti-diagonal is 3 + 5 + 7 = 15. Together they'd be 30, but the center cell (5) is counted twice. The function subtracts 5 once, giving 25 — the sum of the 5 distinct diagonal cells (1, 3, 5, 7, 9). Correct.
Program Output
A typical run:
Enter matrix A (3 rows, 3 columns):
1 2 3
4 5 6
7 8 9
Matrix A:
1 2 3
4 5 6
7 8 9
Main diagonal sum: 15
Anti-diagonal sum: 15
Both diagonals sum to 15 — a nice coincidence for this example. The main diagonal is 1 + 5 + 9 = 15; the anti-diagonal is 3 + 5 + 7 = 15. The center cell (5) is in both diagonals but counted once in each sum (the two sums are computed separately).
A non-symmetric matrix:
Enter matrix A (3 rows, 3 columns):
2 7 1
8 3 6
4 5 9
Matrix A:
2 7 1
8 3 6
4 5 9
Main diagonal sum: 14
Anti-diagonal sum: 8
Main diagonal: 2 + 3 + 9 = 14. Anti-diagonal: 1 + 3 + 4 = 8. Both correct, and the two sums differ — as expected for a general matrix.
An identity matrix:
Enter matrix A (3 rows, 3 columns):
1 0 0
0 1 0
0 0 1
Matrix A:
1 0 0
0 1 0
0 0 1
Main diagonal sum: 3
Anti-diagonal sum: 1
The identity matrix has 1s on the main diagonal (sum = 3) and a single 1 on the anti-diagonal (sum = 1, from the center cell). This is a useful sanity check — the trace of the identity matrix of size n is n.
For the 4×4 example in the variant program:
Main: 34
Anti: 34
Both diagonals sum to 34. For a matrix where A[i][j] = 4*i + j + 1 (as in this example), the main diagonal and anti-diagonal sums happen to coincide. It's not always true — just a coincidence for this particular pattern.
And the combined sum variant:
Combined diagonal sum: 25
The distinct diagonal cells are 1, 3, 5, 7, 9 (5 unique values). Their sum is 25. The center cell 5 appears once in the combined sum, not twice — the correction worked.
Step-by-Step Explanation
Let's look at how the diagonal is indexed and how the single loop captures it.
1. The main diagonal indices
For an n×n matrix, the main diagonal cells are a[0][0], a[1][1], a[2][2], ..., a[n-1][n-1]. The row and column indices are always equal — that's the definition of the main diagonal. So the loop is simply:
for (int i = 0; i < N; i++) sum += a[i][i];
One loop, one index. No nested loops. The diagonal is a 1D slice of a 2D array.
2. The anti-diagonal indices
The anti-diagonal cells are a[0][n-1], a[1][n-2], a[2][n-3], ..., a[n-1][0]. The row index increments from 0 to n-1, while the column index decrements from n-1 to 0. The relation is column = n - 1 - row. So the loop is:
for (int i = 0; i < N; i++) sum += a[i][N - 1 - i];
The N - 1 - i expression is the column index. As i increases from 0 to n-1, this decreases from n-1 to 0 — tracing the anti-diagonal in reverse-column order.
3. Tracing mainDiagonalSum for {{1,2,3},{4,5,6},{7,8,9}}
- sum = 0.
- i=0: sum += a[0][0] = 1. sum = 1.
- i=1: sum += a[1][1] = 5. sum = 6.
- i=2: sum += a[2][2] = 9. sum = 15.
- Loop ends. Return 15. ✓
Three iterations — one per diagonal cell. Compare with summing the entire matrix, which would be a 2D loop of 9 iterations. The diagonal is 3x cheaper for a 3×3 matrix, and the ratio grows as n²/n = n — for a 1000×1000 matrix, the diagonal sum is 1000 operations vs. 1,000,000 for the full sum.
4. Tracing antiDiagonalSum for {{1,2,3},{4,5,6},{7,8,9}}
- sum = 0.
- i=0: sum += a[0][2] = 3. sum = 3.
- i=1: sum += a[1][1] = 5. sum = 8.
- i=2: sum += a[2][0] = 7. sum = 15.
- Loop ends. Return 15. ✓
Also three iterations, summing the other diagonal. The center cell (5) contributes to both sums, but each sum is computed independently.
5. The double-counting problem for combined sums
If a problem asks for "the sum of both diagonals" and you naively add the two sums, you'd count the center cell of odd-sized matrices twice. For example, in the 3×3 example, the two sums are both 15, and adding them gives 30 — but the distinct diagonal cells sum to 25. The discrepancy is exactly the center cell: 5, counted twice in the combined total.
The fix is to subtract the center cell once after summing: if (N % 2 == 1) sum -= a[N/2][N/2];. For even-sized matrices, there's no center cell (the diagonals don't overlap), so no correction is needed. This is a common trick in competitive programming, where problems often ask for "sum of both diagonals without double-counting."
6. Why square matrices only
The main diagonal a[i][i] only makes sense if every row has a column with the same index. For an m×n matrix with m ≠ n, some rows wouldn't have a corresponding column, and the diagonal would be truncated or undefined. So diagonal sums require square matrices — the type int a[N][N] enforces this. If you wanted to compute "the diagonal-like sum" for a non-square matrix, you'd need to define what you mean (the min(m, n) cells? the cells that exist?), which is problem-specific.
7. The trace: a fundamental invariant
The main diagonal sum is called the trace, written tr(A). It has several important properties:
tr(A + B) = tr(A) + tr(B)— trace is linear.tr(AB) = tr(BA)— trace is cyclic (for any matrices A, B where both products are defined).tr(A) = sum of eigenvalues of A— the trace equals the sum of the eigenvalues (counting multiplicity).tr(I) = n— the trace of the n×n identity matrix is n.
These properties make the trace a powerful tool in linear algebra. It appears in the characteristic polynomial (the sum of the roots is the trace), in the definition of the determinant (for small matrices, det depends on the trace), and in many physics formulas (the trace of the stress tensor is 3 times the pressure, for instance). Computing it is trivial; the interesting part is what it reveals.
8. Anti-diagonal sums and related concepts
The anti-diagonal sum is less commonly used in mathematics, but it appears in some contexts:
- Anti-symmetric matrices: matrices where
A[i][j] = -A[j][i]. These have zero anti-diagonal sum only when the diagonal entries are 0 (which they must be). - Persymmetric matrices: matrices symmetric about the anti-diagonal, meaning
A[i][j] = A[N-1-j][N-1-i]. - Chessboard patterns: in problems where cells are colored like a chessboard, the anti-diagonal is one of the diagonals.
Even if the anti-diagonal sum isn't as fundamental as the trace, it's a natural companion and easy to compute. Both functions follow the same pattern — single loop, accumulate — with different index expressions.
9. Complexity
O(n) time — one iteration per diagonal cell. O(1) extra space for the accumulator. This is optimal for the problem — you can't sum the diagonal without touching each cell, and there are n cells. The single-loop structure is the efficiency — no need for a nested loop when the cells lie on a 1D line through the matrix.
10. Generalizations
The concept of "diagonal" generalizes to diagonals at offsets (e.g., a[i][i+k] for some offset k), which appear in image processing (diagonal edge detection) and matrix factorization algorithms (QR decomposition). A matrix is diagonal if only the main diagonal is non-zero; tridiagonal if only the main diagonal and its immediate neighbors are non-zero. These are special matrix structures that allow fast algorithms (e.g., the Thomas algorithm for tridiagonal systems is O(n) instead of O(n³)). Understanding the diagonal as a simple index pattern prepares you for these more complex concepts.
🔍 Try this: modify the program to also compute the sum of the "upper diagonal" (cells just above the main diagonal — a[i][i+1]) and the "lower diagonal" (cells just below — a[i+1][i]). These are used in tridiagonal matrices and finite-difference schemes. Each is another single loop with a shifted index — and they show you how the diagonal pattern extends to nearby offsets.
Frequently Asked Questions
1. Why does the diagonal sum use only one loop?
Because the main diagonal cells are at positions (0,0), (1,1), (2,2), ... — one cell per row, one cell per column, and the same index for both. So a single loop over i is enough: each iteration visits exactly one diagonal cell. A nested loop would visit all n² cells, which is unnecessary. The diagonal is a 1D slice through the 2D array, and a 1D loop is the right way to traverse it. Same for the anti-diagonal — one cell per row, different column index, single loop.
2. Can I compute the diagonal sum for a non-square matrix?
Not in the usual sense. The main diagonal a[i][i] requires that every index i that's valid for rows also be valid for columns — which only happens if the matrix is square. For an m×n matrix with m < n, the "diagonal" would be the cells (0,0), (1,1), ..., (m-1,m-1) — m cells — but "diagonal" isn't really the right term. For m > n, you'd have n cells with the same limitation. If you need to sum some "diagonal-ish" cells in a rectangular matrix, define the exact set of cells first, then write a loop for that set.
3. What's the "trace" of a matrix, and why does it matter?
The trace is the sum of the main diagonal, written tr(A). It's a fundamental invariant in linear algebra: it equals the sum of the eigenvalues (counted with multiplicity), it's invariant under cyclic permutation of matrix products (tr(AB) = tr(BA)), and it appears in many formulas (the characteristic polynomial, the determinant for small matrices, the log-determinant in machine learning, the trace of a stress tensor in physics). Computing it is trivial — our mainDiagonalSum function does exactly that. Its importance is in what it reveals about the matrix's algebraic structure.
4. What is the anti-diagonal?
The anti-diagonal (also called secondary or counter-diagonal) is the cells where row + column = n-1: (0, n-1), (1, n-2), ..., (n-1, 0). It runs from top-right to bottom-left. Its sum is the "anti-trace", which is less commonly used than the trace but appears in problems involving persymmetric matrices, chessboard patterns, and certain numerical algorithms. Our antiDiagonalSum function computes it with the index expression a[i][N-1-i].
5. Why would I want the sum of both diagonals?
Some problems ask for it explicitly — for example, "check if a matrix is a magic square with equal diagonal sums" or "compute the difference between the sums of the two diagonals" (a common coding interview question). For odd-sized matrices, the center cell is on both diagonals, so summing them separately and adding gives a double count. The fix is to subtract the center cell once. For even-sized matrices, the diagonals are disjoint, so the sums can be added directly.
6. Can I compute the diagonal sums in one pass?
Yes — one loop with two accumulators. Each iteration visits one main-diagonal cell and one anti-diagonal cell. For n iterations, you process 2n cells total (but only 2n-1 unique cells for odd n, since the center is visited twice). This single-pass version is faster than two separate loops for large matrices, but the difference is small (the diagonal is O(n), so it's already fast). Still, combining operations in one loop is a good habit that pays off in more complex problems.
💡 Tip: Once this works, try computing the sum of a general diagonal — cells a[i][i+k] for some offset k, valid only for 0 ≤ i < n-k. These are the cells on the k-th super-diagonal. Similarly, a[i+k][i] is the k-th sub-diagonal. Tridiagonal matrices have nonzero cells only on the main diagonal and the ±1 diagonals, and solving systems with them is a classic O(n) algorithm (the Thomas algorithm). Understanding diagonal offsets is the first step toward that family of algorithms.