🔍 Sum of All Elements in a 3x3 Matrix in C

⬅️ Previous

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.

3x3 matrix in C, sum of matrix elements in C, how to calculate sum in C using loop, 2D array sum in C, matrix addition in C example, C language matrix example, matrix calculation using C, simple matrix problem in C, C programming for beginners #CProgramming #MatrixInC #SumMatrix #2DArray #LearnC #CProgram #MatrixCalculation #CMatrix #CodingInC #CProgrammingTutorial #BeginnerCProjects

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ