**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

4 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();

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 to read:*
This comment has been removed by the author.

ReplyDeleteits very useful

ReplyDeletehats off

ReplyDeleteit's so helpful.......................thnx

ReplyDeletehelpfull....lots of thanks

ReplyDeleteIt so halpful for me or us...... so thank you .

ReplyDeleteIt is helpful for me or ur .....so, thank you

ReplyDeleteThank you......*

ReplyDeletethanks.....

ReplyDeletethanxxx

ReplyDeletethanxxxxxxx

ReplyDeletefor(i=0; i<9; i++)

ReplyDelete{

if(i%4==0)

{

sum=sum+a[i];

}

}