Find the sum of the main diagonal elements of a matrix with C.
#include <stdio.h>
int main()
{
int A[3][3];
int row, col, sum = 0;
/* Input elements in matrix from user */
printf("Enter elements in matrix of 3 %dx%d: \n", 3, 3);
for (row = 0; row < 3; row++)
{
for (col = 0; col < 3; col++)
{
scanf("%d", &A[row][col]);
}
}
/* Find sum of main diagonal elements */
for (row = 0; row < 3; row++)
{
sum = sum + A[row][row];
}
printf("\nSum of main diagonal elements = %d", sum);
return 0;
}
Output
Enter elements in matrix of size 3x3 :
1 2 3
4 5 6
7 8 9
Sum of main diagonal elements = 15
0 Comments