C program to find the sum of opposite diagonal elements of a matrix

Write a C program to read elements in a matrix and find the sum of minor diagonal (opposite diagonal) elements. C program to calculate sum of minor diagonal elements.

Example:
If the matrix elements are:
1 2 3
4 5 6
7 8 9

Sum of minor diagonal elements = 15

Required knowledge:

Basic C programming, For loop, Array, Matrix

Minor diagonal of a matrix

Minor diagonal of a matrix A is a collection of elements Aij Such that i + j = N + 1.
Minor diagonal of a matrix

Program:

/**
 * C program to find sum of opposite diagonal elements of a matrix
 */

#include <stdio.h>

int main()
{
    int A[3][3];
    int row, col, sum = 0;

    /*
     * Reads elements in matrix from user
     */
    printf("Enter elements in matrix of size 3x3: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /*
     * Finds the sum of minor diagonal elements
     */
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            /*
             * If it is minor diagonal of matrix
             * Minor diagonal: i+j == N + 1
             * Since array elements starts from 0 hence i+j == (N + 1)-2
             */
            if(row+col == ((3+1)-2))
            {
                sum += A[row][col];
            }
        }
    }

    printf("\nSum of minor diagonal elements = %d", sum);

    return 0;
}
Output
X
_
Enter elements in matrix of size 3x3:
1 2 3
4 5 6
7 8 9

Sum of minor elements = 15

Happy coding ;)


You may also like

Labels: , , ,