Matrices in C: solved exercise
If you are searching for matrices in C solved exercises, this is one of the best tasks to master indexing in 2D arrays.
Problem statement
Given a 3x3 square matrix, compute:
- main diagonal sum,
- secondary diagonal sum.
C solution
#include <stdio.h>
int main(void) {
int m[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int main_sum = 0;
int secondary_sum = 0;
for (int i = 0; i < 3; i++) {
main_sum += m[i][i];
secondary_sum += m[i][2 - i];
}
printf("Main diagonal: %d\n", main_sum);
printf("Secondary diagonal: %d\n", secondary_sum);
return 0;
}Expected output
Main diagonal: 15
Secondary diagonal: 15Recommended edge case
Also test a 1x1 matrix:
{ {7} }
Main diagonal: 7
Secondary diagonal: 7Common mistakes
- Swapping formulas: main is
m[i][i]and secondary ism[i][n - 1 - i]. - Hardcoding
2 - iand breaking the logic for non-3x3sizes. - Not resetting accumulators to
0between test runs. - Using a non-square matrix and expecting diagonal logic to hold.
Time and space complexity
- Time: O(n) to compute both diagonals in an
n x nmatrix. - Extra space: O(1) with only accumulator variables.
Practical use
This indexing pattern appears in table analytics, data transforms, and matrix-based optimization tasks.
Recommended next exercise
- Strings in C: solved exercises with strlen, strcpy, and strcmp
- Files in C: solved exercise to count lines and characters
- Bubble sort in C: solved exercise step by step
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
Is this matrices exercise beginner-friendly?
Yes, this is basic-to-intermediate and excellent for loop and index practice.
Where can I find more solved C exercises?
At Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.
How should I practice this exercise type to improve faster?
Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.