C Program to Find Sum of all Elements of a Matrix

In this tutorial, you will learn and get code about finding the sum of all elements of a given matrix.

The question is Write a C program that takes 9 elements of 3*3 matrix as input from user (at run-time) and calculate the sum of all the matrix elements. The answer to this question is:

int main()
    int mat[3][3], i, j, sum;
    sum = 0;
    printf("Enter all 9 elements of 3*3 Matrix:-\n");
    for(i=0; i<3; i++)
        for(j=0; j<3; j++)
            scanf("%d", &mat[i][j]);
            sum = sum + mat[i][j];
    printf("\nSum of all elements = %d", sum);
    return 0;

The program was written in Code::Blocks IDE, therefore after successful build and run, you will get the output as shown in the sample given here:

c program sum of all elements in matrix

Enter all the 9 elements and press enter key, here is the second screenshot of sample run:

sum of elements in matrix c

Program Explained

  1. Take all 9 elements as input and initialize to the matrix one by one
  2. The 3*3 matrix means, it has 3 rows and 3 columns
  3. We have to use two for loops, outer one is for rows, and inner one is for column
  4. In this way
    • the first element is initialized to mat[0][0]
    • the second element is initialized to mat[0][1]
    • the third element is initialized to mat[0][2]
    • in similar way, the fourth, fifth, sixth, seventh, eight and ninth elements gets initialized to mat[1][0], mat[1][1], mat[1][2], mat[2][0], mat[2][1], mat[2][2]
  5. At the time of scanning every element, the summation statement is applied
  6. Finally print out the value of sum variable. Never forgot to initialize 0 to sum variable before start calculating sum of all the matrix elements

C Online Test

« Previous Program Next Program »

Follow/Like Us on Facebook

Subscribe Us on YouTube