C program to find sum of main diagonal elements of a matrix

Write a C program to read elements in a matrix and find the sum of main diagonal (major diagonal) elements of matrix. Find sum of all elements of main diagonal of a matrix. Logic to find sum of main diagonal elements of a matrix in C programming.

Required knowledge

Basic C programming, C for loop, ArrayS

Main diagonal of matrix

Main diagonal of a matrix A is a collection of elements Aij Such that i = j.

Main diagonal of a matrix

Program to find sum of main diagonal elements of a matrix



 
/**
 * C program to find sum of main 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", SIZE, SIZE);
    for(row=0; row<SIZE; row++)
    {
        for(col=0; col<SIZE; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /* Find sum of main diagonal elements */
    for(row=0; row<SIZE; row++)
    {
        sum = sum + A[row][row];
    }

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

    return 0;
}



Output

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

Main diagonal of matrix




/**
 * C program to find sum of main 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 main diagonal elements */
    for(row=0; row<m; row++)
    {
        sum = sum + A[row][row];
    }

    printf("\nSum of main 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 main diagonal elements = 5
Process returned 0 (0x0) execution time : 9.208 s



Instagram