To find the sum of primary diagonal of a Matrix

Here is the program to find the sum of the primary diagonal elements (From left top to right bottom) of the entered integer matrix. The program asks for the order (M, N)  [where M should equal N] of the matrix. Soon after entering the order, the cursor takes to the proper position in the screen to input the matrices. User need to hit ‘Enter’ button after each entry. Matrix is stored as A.

Logic :  The diagonal elements, are the elements having equal column and row value throughout. By keeping this in mind, we can trace the matrix till the end using the help of a for loop.  The flag ‘sum’ is updated in each of the iterations.
Finally, we’ll get the sum of the diagonal elements after the end of the while loop.

You are always welcome with your suggestion and doubts into our discussion forum.

#include<stdio.h>
void main()
{
int A,i,j,m,n,sum = 0;
clrscr();
printf(“\n\n\t ENTER A ORDER OF THE MATRIX M,N…: “);
scanf(“%d,%d”,&m,&n);
printf(“\n\n\t ENTER THE ELEMENTS OF THE MATRIX..:\n\n”);
if(m == n)
{
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
gotoxy(20+j*4,12+i*2);
scanf(“%d”,&A[i][j]);
}
printf(“\n”);
}
for(i=1;i<=m;i++)
sum = sum + A[i][i];
printf(“\n\t THE SUM OF PRIMARY DIAGONAL OF A MATRIX IS…: %d”, sum);
}
else
{
printf(“\n\t THE ORDER OF THE MATRIX IS NOT CORRECT”);
printf(“\n\n\t HELP : ‘M’ SHOULD BE EQUAL TO ‘N'”);
}
getch();
}

2 Responses to “To find the sum of primary diagonal of a Matrix”

1. this programme is not working.can anyone give correct code to this. send it to:email id:[email protected]

2. Anonymous

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

please find attached the program to find the sum of diagonals of a matrix.

please have a look at the following link to have an indepth understanding of the problem

More from Matrix Programs
Robotic car using 8951 Microcontroller Research Papers Projects 