C/C++ Program to find the sum of all elements of a matrix

Write a program in C to find the sum of all elements of a matrix.

For exampe,

Input
{
     {1, 2, 4}
     {1, 3, 0}
     {2, 3, 5}
 }
Output
21
Explaination
1 + 2 + 4 + 1 + 3 + 0 + 2 + 3 + 5 = 21

This problem is very simple. First, we will declare a temporary variable sum = 0 to store the sum. After that, we will use a nested loop to read all the elements of the matrix and add each element to sum.

 #include<stdio.h>
  
 // function to find sum of all elements of matrix mat
 // n is the number of rows in A
 // m is the number of columns in A
 int SumOfMatrix(int mat[][20], int n, int m)
 {
  
                int sum = 0, i, j;
  
                for (i = 0; i < n; ++i) {
                               for (j = 0; j < m; ++j) {
                                              sum += mat[i][j];
                               }
                }
  
                return sum;
  
 }
  
 int main()
 {
                int i, j, n, m, mat[20][20];
  
                printf("Enter Rows in the Matrix: ");
                scanf("%d", &n);
  
                printf("Enter Columns in the Matrix: ");
                scanf("%d", &m);
  
  
                printf("Enter Matrix Elements:\n");
                for (i = 0; i < n; ++i) {
                               for (j = 0; j < m; ++j) {
                                              scanf("%d", &mat[i][j]);
                               }
                }
  
                printf("\nSum of all elements of Matrix is = %d", SumOfMatrix(mat, n, m));
  
 } 

Output

 Enter Rows in the Matrix: 3
 Enter Columns in the Matrix: 3
 Enter Matrix Elements:
 1 2 4
 1 3 0
 2 3 5
 Sum of all elements of Matrix is = 21

Read

Leave a Comment

Your email address will not be published. Required fields are marked *