WAP that finds the sum of diagonal elements of a mxn matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int mat[10][10],i,j,m,n,dg1=0,dg2=0;
clrscr();
printf("\n Input number of rows and columns of matrix\n");
scanf("%d%d",&m,&n);
if(m!=n)
{
printf("\n rows and columns are not same so diagonal sum cannot be calculated");
getch();
exit(0);
}
else
{
printf("\n Enter matrix elements :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&mat[i][j]);
if(i==j)
dg1=dg1+mat[i][j];
if(i+j==m-1)
dg2=dg2+mat[i][j];
}
}
printf("\n Matrix elements are \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d", mat[i][j]);
}
printf("\n");
}
printf("\n Sum of diagonal 1 :%d",dg1);
printf("\n Sum of diagonl 2 :%d",dg2);
}
getch();
}
Output:-1
Input number of rows and columns of matrix
2
3
rows and columns are not same so diagonal sum cannot be calculated
Output:-2
Input number of rows and columns of matrix
3
3
Enter matrix elements
1
2
3
4
5
6
7
8
9
Matrix elements are
1 2 3
4 5 6
7 8 9
Sum of diagonal 1 :15
Sum of diagonal 2 :15


0 Comments