Diagonal sum of matrix

Q. Write a C program to find the sum of diagonal elements in matrix.
Hint: If you have following typical square 3X3 matrix, then diagonal elements will be:

1  2  3
5  6
7  8  9

In above 3X3 matrix there are two types diagonal element as:
first diagonal elements are  1, 5, 9 and
second diagonal elements are 3, 5,7

Ans.

/*program to find the sum of diagonal elements of the matrix*/
#include<stdio.h>
#include<conio.h>
#define MAX 5
int main()
{
  int mat[MAX][MAX],row,col;
  int i,j,d1=0,d2=0;
  printf("Enter no. of rows and columns : ");
  scanf("%d%d",&row,&col);
  printf("Enter the elements of matrix:\n");
  if(row==col)
  {
    for(i=0; i<row; i++)
    {
      for(j=0; j<col; j++)
         scanf("%d",&mat[i][j]);
    }
    for(i=0,j=col-1; i<row || j>=0; i++,j--)
    {
       d1=d1+mat[i][i];
       d2=d2+mat[i][j];
    }
    printf("\nThe sum of first diagonal elements : %d",d1);
    printf("\nThe sum of second diagonal elements : %d",d2);
  }
  else
  {
     printf("Rows and columns are not equal!");
     printf("\nTry again!");
  }
  getch();
  return 0;
}

output:-

Enter no. of rows and columns : 3  2
Enter the elements of matrix:
Rows and columns are not equal!
Try again!

Enter no. of rows and columns : 3 3
Enter the elements of matrix:
1  2  3
4  5  6
7  8  9
The sum of first diagonal elements : 15
The sum of second diagonal elements : 15 

You might also like:
  1. Difference of two matrix C program
  2. Transpose of matrix C program
  3. Product of matrix C program
  4. Sum of matrix C program

Comments