Sum of All Elements in a 3x3 Matrix in C
Problem:
Write a C program to calculate the sum of all elements in a 3x3 matrix.
đ Explanation:
- A 3x3 matrix contains 9 elements.
- Use a 2D array
matrix[3][3]
to store values. - As each number is entered, it is added to a variable
sum
. - The final sum is printed after all elements are processed.
✅ C Program:
#include <stdio.h>
int main() {
int matrix[3][3];
int sum = 0;
// Input the matrix elements
printf("Enter 9 elements of 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
sum += matrix[i][j]; // Add to sum
}
}
// Display the matrix
printf("The 3x3 matrix is:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
// Output the sum
printf("Sum of all elements = %d\n", sum);
return 0;
}
đ¤ Sample Output:
The 3x3 matrix is: 1 2 3 4 5 6 7 8 9 Sum of all elements = 45
đĄ Tip:
- You can use different sizes like 2x2 or 4x4 by changing the loop ranges and array size.
- Direct summing during input makes the code efficient.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ