Find sum of all Matrix elements – GeeksforGeeks

View Discussion

Improve Article

Save Article

Like article

View Discussion

Improve Article

Save Article

Like article

Given a matrix mat[][]the task is to find the sum of all the elements of the matrix.

Examples:

input: mat[][] = {{1, 2, 3}, {4, 5, 6}}
Output: 21
Explanation: Here sum of all elements = 1 + 2 + 3 + 4 + 5 + 6 = 21

input: mat[][] = {{4, 5, 3, 2}, {9, 5, 6, 2}, {1, 5, 3, 5}}
Output: 50
Explanation: Here sum of all elements = 4 + 5 + 3 + 2 + 9 + 5 + 6 + 2 + 1 + 5 + 3 + 5 = 50

Approach: This can be solved using the following idea:

Traverse through the entire matrix and add the value of the element with the result.

Follow the steps mentioned below to solve the problem:

  • Initialize the variable sum = 0 to store the sum of the matrix.
  • Run a loop to traverse each row of the matrix.
    • Use a nested loop to traverse the columns of the matrix for each row.
      • Add each element to the variable sum.
  • Return sum as the required answer.

Pseudo Code:

sum = 0
for i = 0 to N-1:
for j = 0 to M-1:
sum = sum + mat[i][j]
return sum

Below is the implementation of the above approach:

C++

 

#include <bits/stdc++.h>

using namespace std;

 

int sumOfMatrix(int N, int M, vector<vector<int> > mat)

{

    

    

    int sum = 0;

 

    

    for (int i = 0; i < N; i++) {

 

        

        for (int j = 0; j < M; j++) {

 

            

            sum += mat[i][j];

        }

    }

 

    

    return sum;

}

 

int main()

{

    

    vector<vector<int> > mat = { { 4, 5, 3, 2 },

                                 { 9, 5, 6, 2 },

                                 { 1, 5, 3, 5 } };

 

    int N = mat.size();

    int M = mat[0].size();

 

    

    cout << sumOfMatrix(N, M, mat) << endl;

 

    return 0;

}

Time Complexity: O(N * M), where N is the number of rows and M is the number of columns in the given matrix
Auxiliary Space: O(1)

Source link

4 thoughts on “Find sum of all Matrix elements – GeeksforGeeks”

Leave a Comment

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

Scroll to Top