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.

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

Output: Sum of main diagonal elements = 15

Required knowledge:

Basic C programming, For loop, Array, Matrix

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:

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

    printf("\nSum of main 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 main diagonal elements = 15

Happy coding ;)


You may also like

Labels: , , ,