Q)Write a C program to find the sum of diagonal elements in matrix.
Hint:
1 2 3
4 5 6
7 8 9
First diagonal elements are 1,5,9
Second diagonal elements are 3,5,7.
Sol)
#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("\n The sum of second diagonal elements : %d", d2) ;
}
else
{
printf("Rows and Columns are not equal !!") ;
printf("\n Try 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