# Find sum of all Matrix elements – GeeksforGeeks

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 ` `using` `namespace` `std;` ` ` `int` `sumOfMatrix(``int` `N, ``int` `M, vector > 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 > mat = { { 4, 5, 3, 2 },` `                                 ``{ 9, 5, 6, 2 },` `                                 ``{ 1, 5, 3, 5 } };` ` ` `    ``int` `N = mat.size();` `    ``int` `M = mat.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)