Sum of the Main Diagonal of a 4x4 Matrix in C
Problem: Calculate the sum of the main diagonal of a 4x4 matrix.
đ Explanation:
- The main diagonal elements have equal row and column indices.
- Sum these elements using a loop where
i == j
.
✅ C Program:
#include <stdio.h>
int main() {
int matrix[4][4];
int diagonalSum = 0;
printf("Enter 16 elements of 4x4 matrix:\n");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
scanf("%d", &matrix[i][j]);
}
}
for (int i = 0; i < 4; i++) {
diagonalSum += matrix[i][i];
}
printf("Sum of the main diagonal = %d\n", diagonalSum);
return 0;
}
đ¤ Sample Output:
Sum of the main diagonal = 34
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ