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

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

This C program is to find the sum of diagonal elements of a square matrix.For example, for a 2 x 2 matrix, the sum of diagonal elements of the matrix {1,2,3,4} will be equal to 5.

1     2

3    4

 Sum = 1+4 = 5

Logic

Here the procedure is almost same as the sum of elements of a matrix, only one condition needs to be added which is, we add only those elements of the matrix for which row number and column number is same, like 1st row and 1st column, 2nd row and 2nd column and so on(i==j).

Dry Run of the Program

Take input mat[][] and store elements in mat{1,2}{3,4}

Take input ‘row’ and no of rows(row) as 2

Take input ‘col’ and no of columns(col) as 2

Initialize sum=0

1st iteration for(i=0;i<row;i++) i.e. for(i=0;0<2;i++) Outer loop

1st iteration for(j=0;j<col;j++) i.e. for(j=0;0<2;j++) Inner loop

if(i==j) i.e. if(0==0)   true

sum=sum+mat[i][j];  i.e.  sum=0+mat[0][0] i.e. sum=0+1  i.e. sum=1

2nd iteration for(j=1;j<col;j++) i.e. for(j=1;1<2;j++) Inner loop

if(i==j) i.e. if(0==1)   false

2nd iteration for(i=1;i<row;i++) i.e. for(i=1;1<2;i++) Outer loop

1st iteration for(j=0;j<col;j++) i.e. for(j=0;0<2;j++) Inner loop

if(i==j) i.e. if(1==0)   false

2nd iteration for(j=1;j<col;j++) i.e. for(j=1;1<2;j++) Inner loop

if(i==j) i.e. if(1==1)   true

sum=sum+mat[i][j];  i.e.  sum=1+mat[1][1] i.e. sum=1+4  i.e. sum=5

Now we break out of inner loop and then outer loop.

Hence the sum of diagonal elements of a square matrix[1,2][3,4] would be sum=5

Program

#include<stdio.h>

void main()
{
    int mat[12][12];
    int i,j,row,col,sum=0;
    printf("Enter the number of rows and columns for 1st matrix\n");
    scanf("%d%d",&row,&col);
    printf("Enter the elements of the matrix\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            scanf("%d",&mat[i][j]);
        }
    }

    printf("The matrix\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            printf("%d\t",mat[i][j]);
        }
        printf("\n");
    }
    //To add diagonal elements
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            if(i==j)
            {
                sum=sum+mat[i][j];
            }
        }
    }

    printf("The sum of diagonal elements of a square matrix = %d\n",sum);
}

Output

Share Me!