C Program to add principal diagonal elements in a matrix
Program
#include<stdio.h>
void main()
{
int i, j, mat[10][10], row, col;
int sum = 0;
printf("Enter the number of Rows:\t");
scanf("%d", &row);
printf("Enter the number of Columns:\t");
scanf("%d", &col);
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("\nEnter the Element a[%d][%d] : ", i, j);
scanf("%d", &mat[i][j]);
}
}
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (i == j)
sum = sum + mat[i][j];
}
}
printf("\nSum of Diagonal Elements in Matrix : %d\n", sum);
}
Output
Enter the number of Rows: 3
Enter the number of Columns: 3
Enter the Element a[0][0] : 12
Enter the Element a[0][1] : 33
Enter the Element a[0][2] : 43
Enter the Element a[1][0] : 1
Enter the Element a[1][1] : 56
Enter the Element a[1][2] : 32
Enter the Element a[2][0] : 99
Enter the Element a[2][1] : 85
Enter the Element a[2][2] : 10
Sum of Diagonal Elements in Matrix : 78