Addition of Diagonal Elements in Matrix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include<stdio.h> int main() { int i, j, mat[10][10], row, col; int sum = 0; printf("\nEnter the number of Rows : "); scanf("%d", &row); printf("\nEnter the number of Columns : "); scanf("%d", &col); //Accept the Elements in m x n Matrix 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]); } } //Addition of all Diagonal Elements for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (i == j) sum = sum + mat[i][j]; } } //Print out the Result printf("\nSum of Diagonal Elements in Matrix : %d", sum); return (0); } |
Output
1 2 3 4 5 6 7 8 9 10 | Enter the number of Rows : 2 Enter the number of Columns : 2 Enter the Element a[0][0] : 1 Enter the Element a[0][1] : 1 Enter the Element a[1][0] : 1 Enter the Element a[1][1] : 1 The Addition of All Elements in the Matrix : 2 |
Explanation :
Considering above 3×3 matrix -
- We have to add a[0][0],a[1][1],a[2][2]
- By Observing , it is clear that when i = j Condition is true then and then only we have to add the elements