C Program to find sum elements in each row,column and sum of the principle diagonals of a matrix.

 


#include<stdio.h>

main()

{

int a[20][20],n,i,j,diagonal,rowsum,colsum,m;

clrscr();

printf("\nEnter the Dimensions of the Matrix (M*N)\n");

scanf("%d%d",&m,&n);

if(m==n)

{

printf("\nEnter the matrix elements:\n");

for(i=0;i<m;i++)

{

for(j=0;j<n;j++)

{

scanf("%d",&a[i][j]);

}

}

printf("\nThe Given MAtrix is:\n");

for(i=0;i<m;i++)

{

for(j=0;j<n;j++)

{

printf("%d\t",a[i][j]);

}

printf("\n");

}

for(i=0;i<m;i++)

{

a[i][n]=0;

for(j=0;j<n;j++)

{

a[i][n]=a[i][n]+a[i][j];

}

printf("\nRow sum=%d",a[i][n]);

}

printf("\n");

for(i=0;i<n;i++)

{

a[n][i]=0;

for(j=0;j<n;j++)

{

a[n][i]=a[n][i]+a[j][i];

}

printf("\nColumn Sum= %d",a[n][i]);

}

printf("\n");

a[n][n]=0;

for(i=0;i<n;i++)

{

a[n][n]=a[n][n]+a[i][i];

printf("\nSum of principle diagonal is: %d",a[n][n]);

}

printf("\nElements of given matrix along with row, column and principle  

                   diagonal sum:\n");

for(i=0;i<=n;i++)

{

for(j=0;j<=m;j++)

{

printf("%5d",a[i][j]);

}

printf("\n");

}

}

           getch();

}




Output:

Enter the Dimensions of the Matrix (M*N)

  1. 3

Enter the matrix elements:

1 2 3 4 5 6 7 8 9


The Given Matrix is:

1       2       3

4       5       6

7       8       9


Row sum=6

Row sum=15

Row sum=24


Column Sum= 12

Column Sum= 15

Column Sum= 18


Sum of principle diagonal is: 1

Sum of principle diagonal is: 6

Sum of principle diagonal is: 15


Elements of given matrix along with row, column, and principle diagonal sum:       


  1    2    3    6

           4    5    6   15

           7    8    9   24

           1   2   15   18   15


Post a Comment

Previous Post Next Post