Matrices in C: solved main and secondary diagonal exercise

  2 minutes

If you are searching for matrices in C solved exercises, this is one of the best tasks to master indexing in 2D arrays.

Given a 3x3 square matrix, compute:

  • main diagonal sum,
  • secondary diagonal sum.
#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;
}
Main diagonal: 15
Secondary diagonal: 15

Also test a 1x1 matrix:

{ {7} }
Main diagonal: 7
Secondary diagonal: 7
  • Swapping formulas: main is m[i][i] and secondary is m[i][n - 1 - i].
  • Hardcoding 2 - i and breaking the logic for non-3x3 sizes.
  • Not resetting accumulators to 0 between test runs.
  • Using a non-square matrix and expecting diagonal logic to hold.
  • Time: O(n) to compute both diagonals in an n x n matrix.
  • Extra space: O(1) with only accumulator variables.

This indexing pattern appears in table analytics, data transforms, and matrix-based optimization tasks.

If you want a complete path with progressive difficulty:

Yes, this is basic-to-intermediate and excellent for loop and index practice.

At Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.