Search



Friday, 27 February 2015

sum of both diagonal elements of matrix

In this algorithm , we have to find the sum of both diagonals of matrix . Supoose a 2d matrix , then it has 2 diagonals i.e left diagonal & right diagonal . So, in left diagonal ( \ in this way) , i==j like a[1][1] , a[2][2] & in right diagonal ( / in this way) i+j == m-l; so when the conditions of these diagonals is true, the element is added in variable sum . & hence the sum of both diagonals is found .

#include<stdio.h>
#include<conio.h>
void main()
{ int a[10][10],i,j,m,sum_right=0,sumleft=0;
clrscr();
printf("\n program to find sum of diagonal elements of matrix");
printf("\n (rows & columns should be same)");
printf("\n\n enter no. of rows & cloumns : ");
scanf("%d",&m);
printf("\n now enter them : \n");
for(i=0;i<m;i++)
{       for(j=0;j<m;j++)
{ printf("enter a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
if((i+j)==(m-1))
{ sum_right = sum_right + a[i][j];
}
if(i==j)
{ sumleft = sumleft + a[i][j];
}
}
}
printf("\n displaying matrix : \n");
for(i=0;i<m;i++)
{       for(j=0;j<m;j++)
{ printf("\t a[%d][%d] = %d",i,j,a[i][j]);
}
printf("\n");
}
printf("sum of left diagonal elements = %d",sumleft);
printf("sum of right diagonal elements = %d",sum_right);
getch();
}

No comments:

Post a Comment

Guys if you think something is wrong or should be edit than please do comment.