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. Logic to find sum of opposite diagonal elements of a matrix in C programming.

Required knowledge

Basic C programming, C for loop, ArrayS

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 to find sum of opposite diagonal elements of a matrix




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

#include <stdio.h>

#define SIZE 3 // Matrix size

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

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

    /* Find sum of minor diagonal elements */
    for(row=0; row<SIZE; row++)
    {
        for(col=0; col>SIZE; 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 == ((SIZE+1)-2))
            {
                sum += A[row][col];
            }
        }
    }

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

    return 0;
}



Output
Enter elements in matrix of size 3x3:
90 80 70
60 50 40
30 20 10
Sum of minor diagonal elements = 150
Process returned 0 (0x0) execution time : 34.726 s



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

#include 

int main()
{
    int A[10][10];
    int row, col, sum = 0,m,n;
    printf("Enter number of rows:");
    scanf("%d",&m);
    printf("Enter number of columns:");
    scanf("%d",&n);
    /* Input elements in matrix from user */
    printf("Enter elements in matrix of size %dx%d: \n",m,n);
    for(row=0; row<m; row++)
    {
        for(col=0; col<n; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /* Find sum of minor diagonal elements */
    for(row=0; row<m; row++)
    {
        for(col=0; col<n; 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 == ((m+1)-2))
            {
                sum += A[row][col];
            }
        }
    }

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

    return 0;
}



Output:

Enter number of rows:2
Enter number of columns:2
Enter elements in matrix of size 2x2:
1 2
3 4
Sum of minor diagonal elements = 5
Process returned 0 (0x0) execution time : 6.973 s



Instagram