C program to find the sum of diagonal elements of an array

Last updated on 10th February 2023

The diagonal of a matrix refers to the elements that fall on a line drawn from the top left to the bottom right corner of the matrix. Diagonal elements of a matrix Aij consists of elements of that matrix where i = j. Here i and j are row and column indices respectively. This set of elements is also known as the main diagonal or principal diagonal elements.

Similarly, the elements that fall on a line drawn from the top right to the bottom left corner of a matrix are called antidiagonal or secondary diagonal elements.

For example, the main diagonal of matrix A contains elements 1, 5 and 9 and antidiagonal contains elements 3, 5 and 7.

Matrix Diagonals

Here is a C program to find the sum of diagonal elements of a matrix.

#include <stdio.h>
#define MAX 10

int main() {
    int row, col;
    int a[MAX][MAX];
    int sum = 0;
    
    // Read the matrix
    printf("Enter number of rows and columns of the matrix: ");
    scanf("%d%d", &row, &col);
    
    printf("Enter elements of the matrix:\n");
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)
            scanf("%d", &a[i][j]);

     // Calculate diagonal sum
     for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++) 
            if(i == j)
                sum += a[i][j];
            
     // Print result
     printf("Sum of diagonal elements of the matrix is %d", sum);
     return 0;
}

Output:

Enter number of rows and columns of the matrix: 3 3
Enter elements of the matrix:
1 5 6
3 4 2
2 1 5
Sum of diagonal elements of the matrix is 10

Sum of secondary diagonal elements

Here is a C program to find the sum of secondary diagonal or antidiagonal elements of an array.

#include <stdio.h>
#define MAX 10

int main() {
    int row, col;
    int a[MAX][MAX];
    int sum = 0;
    
    // Read the matrix
    printf("Enter number of rows and columns of the matrix: ");
    scanf("%d%d", &row, &col);
    printf("Enter elements of the matrix:\n");
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)
            scanf("%d", &a[i][j]);

     //Initialize the result matrix to 0
     for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++) 
            if(j == (col - (i + 1)))
                sum += a[i][j];
            
    // Print result matrix
    printf("Sum of anti-diagonal elements of the matrix is %d", sum);
    return 0;
}

Output:

Enter number of rows and columns of the matrix: 3 3
Enter elements of the matrix:
1 5 6
3 4 2
2 1 5
Sum of anti-diagonal elements of the matrix is 12

Feel free to post any questions you may have in the comments.


Post a comment

Comments

Nothing yet..be the first to share wisdom.