C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Sum of diagonals of a Square Matrix

C Program: Sum of Main and Secondary Diagonals of a Matrix

C

#include <stdio.h>

 

int main() {

    int a[10][10];

    int i, j, n;

    int mainDiagSum = 0, secDiagSum = 0;

 

    // Input order of square matrix

    printf("Enter the order of square matrix (n x n): ");

    scanf("%d", &n);

 

    // Input matrix elements

    printf("\nEnter elements of the matrix:\n");

    for (i = 0; i < n; i++) {

        for (j = 0; j < n; j++) {

            scanf("%d", &a[i][j]);

        }

    }

 

    // Calculate sums of main and secondary diagonals

    for (i = 0; i < n; i++) {

        for (j = 0; j < n; j++) {

            if (i == j)

                mainDiagSum += a[i][j];           // Main diagonal (top-left to bottom-right)

            if (i + j == n - 1)

                secDiagSum += a[i][j];            // Secondary diagonal (top-right to bottom-left)

        }

    }

 

    // Display matrix

    printf("\nMatrix:\n");

    for (i = 0; i < n; i++) {

        for (j = 0; j < n; j++) {

            printf("%d\t", a[i][j]);

        }

        printf("\n");

    }

 

    // Display diagonal sums

    printf("\nSum of Main Diagonal Elements = %d\n", mainDiagSum);

    printf("Sum of Secondary Diagonal Elements = %d\n", secDiagSum);

 

    return 0;

}

Output

 
INPUT :
Enter the order of square matrix (n x n): 3
Enter elements of the matrix:
1 2 3
4 5 6
7 8 9

OUTPUT :
Matrix:
1   2   3
4   5   6
7   8   9

Sum of Main Diagonal Elements = 15
Sum of Secondary Diagonal Elements = 15

Explanation

  1. A square matrix has the same number of rows and columns (n x n).
  2. The main diagonal consists of elements where i == j.
  3. The secondary diagonal consists of elements where i + j == n - 1.
  4. Both sums are computed separately using nested loops.