Skip to main content

Sum of both diagonals of matrix

Short answer

For an N×N matrix, principal diagonal elements have i = j, secondary diagonal i + j = N-1. Sum both in one loop: add a[i][i] to d1 and a[i][N-1-i] to d2. For matrix 1 2 3 / 4 5 6 / 7 8 9, both sums are 15.

Write a program to read a square matrix of size N×N and find sum of both diagonals.

For an N×N matrix a[i][j]:

  • Principal (main) diagonal: elements with i = j, that is a[i][i].
  • Secondary diagonal: elements with i + j = N − 1, that is a[i][N−1−i].

One loop from 0 to N−1 adds both.

#include <stdio.h>

int main(void)
{
    int a[10][10], n, i, j, d1 = 0, d2 = 0;
    printf("Enter order N of the square matrix: ");
    scanf("%d", &n);
    printf("Enter %d elements:\n", n * n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &a[i][j]);

    for (i = 0; i < n; i++) {
        d1 += a[i][i];            /* principal diagonal */
        d2 += a[i][n - 1 - i];    /* secondary diagonal */
    }
    printf("Sum of principal diagonal = %d\n", d1);
    printf("Sum of secondary diagonal = %d\n", d2);
    return 0;
}

Sample run (matrix 1 2 3 / 4 5 6 / 7 8 9)

Input: 3 1 2 3 4 5 6 7 8 9

Enter order N of the square matrix: Enter 9 elements:
Sum of principal diagonal = 15
Sum of secondary diagonal = 15

Main diagonal: 1 + 5 + 9 = 15; secondary diagonal: 3 + 5 + 7 = 15. (The centre element is counted in both sums when N is odd.)

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →