Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Matrix Diagonal Sum in C
Sum the principal and secondary diagonals of a square matrix using one loop and simple index math.
A square matrix has two famous diagonals, and adding them up is one of the best small exercises in this free C programming course. In this lecture you will write a matrix diagonal sum in C that touches only the cells it needs, using a single loop instead of a nested one. The same index pattern appears in real embedded C programming: the sum of the principal diagonal of a rotation matrix, called its trace, is what a drone or robot uses to recover a rotation angle from an IMU. This free C tutorial explains the maths, the code, and the traps.
What You Will Learn
- Which cells belong to the principal diagonal and which to the secondary diagonal
- The two index rules,
i == jandi + j == n - 1, and how they collapse into one loop - How to write a matrix diagonal sum in C that works for any square size
- Why the centre cell of an odd-sized matrix is counted by both diagonals
- How to pass a 2-D array to a function as a flat pointer plus a size
Prerequisites
You need to know how a two-dimensional array is declared and initialised, and how a function receives a pointer. The earlier lecture on checking distinct elements introduced the row-major idea, which we use again here.
Matrix Diagonal Sum Basics: The Two Diagonals
Only a square matrix (same number of rows and columns) has diagonals in the usual sense. We call the line from the top-left corner to the bottom-right corner the principal diagonal (or main diagonal). The line from the top-right corner to the bottom-left corner is the secondary diagonal (anti-diagonal).
Principal diagonal of a 4 x 4 matrix (highlighted cells)
| Row | Col 0 | Col 1 | Col 2 | Col 3 |
|---|---|---|---|---|
| 0 | 3 | 1 | 4 | 1 |
| 1 | 5 | 9 | 2 | 6 |
| 2 | 5 | 3 | 5 | 8 |
| 3 | 9 | 7 | 9 | 3 |
Secondary diagonal of the same matrix (highlighted cells)
| Row | Col 0 | Col 1 | Col 2 | Col 3 |
|---|---|---|---|---|
| 0 | 3 | 1 | 4 | 1 |
| 1 | 5 | 9 | 2 | 6 |
| 2 | 5 | 3 | 5 | 8 |
| 3 | 9 | 7 | 9 | 3 |
By hand: the principal diagonal gives 3 + 9 + 5 + 3 = 20, and the secondary diagonal gives 1 + 2 + 3 + 9 = 15. Keep these two numbers in mind; the program must print the same values.
The Index Rules
| Diagonal | Rule for cell (row i, column j) | Cell visited at step k |
|---|---|---|
| Principal | i == j | (k, k) |
| Secondary | i + j == n – 1 | (k, n – 1 – k) |
A beginner’s version loops over every row and column and tests the rule with an if. That visits n x n cells to collect only n of them. Because each diagonal has exactly one cell in every row, you can skip the inner loop entirely and walk down the rows once. The work drops from O(n squared) to O(n).
Matrix Diagonal Sum in C: The Program
The function below accepts the matrix as a flat const int * plus the size n. A C 2-D array is stored row after row with no gaps, so cell (r, c) of an n x n matrix sits at offset r * n + c. Passing the address of the first element works for any n, with no need to hard-code the column count.
Program: ex52a.c
/* ex52a.c - principal and secondary diagonal sums of an n x n matrix */
#include <stdio.h>
static void diagonal_sums(const int *m, int n, int *principal, int *secondary)
{
*principal = 0;
*secondary = 0;
for (int i = 0; i < n; i++) {
*principal += m[i * n + i]; /* (0,0) (1,1) (2,2) ... */
*secondary += m[i * n + (n - 1 - i)]; /* (0,n-1) (1,n-2) ... */
}
}
static void analyse(const char *name, const int *m, int n)
{
int p, s;
int centre = (n % 2 == 1) ? m[(n / 2) * n + (n / 2)] : 0;
diagonal_sums(m, n, &p, &s);
printf("%s (%dx%d)\n", name, n, n);
printf(" principal diagonal sum : %d\n", p);
printf(" secondary diagonal sum : %d\n", s);
printf(" both together, centre counted once : %d\n", p + s - centre);
}
int main(void)
{
int even4[4][4] = {
{ 3, 1, 4, 1 },
{ 5, 9, 2, 6 },
{ 5, 3, 5, 8 },
{ 9, 7, 9, 3 }
};
int odd3[3][3] = {
{ 7, 2, 9 },
{ 4, 6, 1 },
{ 8, 3, 5 }
};
analyse("even4", &even4[0][0], 4);
analyse("odd3", &odd3[0][0], 3);
return 0;
}
Reading the Code
m[i * n + i]is the principal cell of row i.m[i * n + (n - 1 - i)]is the secondary cell of the same row.- The two results leave the function through the pointers
principalandsecondary. - The call
&even4[0][0]passes the address of the very first element. A 2-D array is laid out as one contiguous block, so this flat-pointer idiom is the standard way to hand any n x n matrix to a size-independent function. (A strict reading of the C standard frowns on stepping across rows from a pointer to the first element, but it works on every real compiler and is widely used in embedded code.) centreexists only when n is odd, because only then does one cell lie on both diagonals. For even n the two diagonals never touch.
One loop, two cells per step (n = 4)
Build and Run
gcc -std=c11 -Wall -Wextra -o ex52a ex52a.c
./ex52a
Expected output:
even4 (4x4)
principal diagonal sum : 20
secondary diagonal sum : 15
both together, centre counted once : 35
odd3 (3x3)
principal diagonal sum : 18
secondary diagonal sum : 23
both together, centre counted once : 35
The even4 results, 20 and 15, match the hand calculation. For the 3 x 3 matrix, the principal diagonal is 7 + 6 + 5 = 18 and the secondary is 9 + 6 + 8 = 23. The centre value 6 appears in both, so adding the diagonals naively gives 41, while counting the shared cell once gives 35.
The Centre Cell Trap
Real-World Uses
- Trace of a rotation matrix: for a 3 x 3 rotation matrix the principal diagonal sum equals 1 plus twice the cosine of the rotation angle, so a sensor-fusion routine can read an angle without a full decomposition.
- Image and signal processing: diagonal sums of small kernels act as quick checks for symmetry.
- Games and puzzles: tic-tac-toe, Sudoku and magic square checkers all test both diagonals. The next lecture builds on this directly.
- Linear algebra routines: the trace appears in Kalman filter code and covariance checks.
Common Mistakes and Troubleshooting
- Writing n – i for the secondary column. Arrays start at 0, so the last column is n – 1. Using n – i reads one cell past the row on the first step.
- Applying the code to a non-square matrix. A 3 x 4 matrix has no true diagonals. Add a check or an assertion that rows equal columns.
- Forgetting the centre overlap when the problem asks for a combined total on an odd-sized matrix.
- Integer overflow. Adding many large
intvalues can overflow, which is undefined behaviour for signed types. Use a wider accumulator such aslong longorint64_twhen values can be large. - Passing a pointer-to-pointer. A true 2-D array is not an
int **. Pass&m[0][0]or use a typed parameter.
Best Practices for Matrix Diagonal Sum Code
- For any matrix diagonal sum, walk only the cells you need. A single loop beats a nested loop with an
ifon every embedded target. - Keep the matrix size in a named constant or a parameter, never a magic number scattered through the code.
- On small microcontrollers without a hardware multiplier,
i * n + ican be replaced by a running index that grows byn + 1for the principal diagonal andn - 1for the secondary one. - Validate the size before use when it arrives from outside the program. A wrong n turns the loop into an out-of-bounds read.
Summary and Key Takeaways
- Principal diagonal: cells where row equals column. Secondary diagonal: cells where row plus column equals n – 1.
- One loop from 0 to n – 1 is enough for both, so the work is O(n).
- Odd-sized matrices share one centre cell between the diagonals.
- A 2-D array is one contiguous block, so a flat pointer plus the size describes it fully.
With this matrix diagonal sum in C and the matrix diagonal sum formulas above you now have the first building block of the magic square checker, which is the topic of the next lecture in this free embedded C course.
Frequently Asked Questions
How do I find the matrix diagonal sum in C for any size?
Pass a pointer to the first element and the size n, then loop i from 0 to n – 1 adding m[i*n + i] for the principal diagonal and m[i*n + (n-1-i)] for the secondary diagonal.
What is the difference between the principal and secondary diagonal?
The principal diagonal runs from top-left to bottom-right, where row equals column. The secondary diagonal runs from top-right to bottom-left, where row plus column equals n – 1.
Do non-square matrices have diagonals?
Mathematically you can define a main diagonal for a rectangular matrix, but the secondary diagonal and this exercise assume a square matrix. Check rows equal columns first.
Why does the centre element count twice on odd sizes?
For odd n the middle row and middle column meet at one cell that satisfies both i == j and i + j == n – 1, so both loops add it.
Can I pass a 2-D array to a function without knowing its size?
Yes, by passing a flat pointer and the dimensions as separate parameters, as this lecture does. Another option is a variable length array parameter, which needs C99 or later.
Is the nested-loop version wrong?
No, it gives the same answer, but it visits n squared cells to use only n of them. For tiny matrices the difference is invisible; for large ones the single loop is far faster.
Keep Building Your Embedded C Skills
This lecture is part of the EmbeddedPathashala free C programming course, a free C tutorial written for students who want to write solid embedded C programming code. Compile every program yourself, change the data, and break things on purpose.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments