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.

Example

Input

Input array elements: 
1 2 3
4 5 6
7 8 9

Output

Sum of main diagonal elements = 15

Required knowledge

Basic C programming, For loop, Array

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

Read more - Program to find sum of opposite diagonal elements 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:
1 2 3
4 5 6
7 8 9

Sum of main diagonal elements = 15

Happy coding 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols. as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>