VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-sum-of-all-matrix-elements/

⇱ Sum of all Matrix elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of all Matrix elements

Last Updated : 6 May, 2026

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 element = 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 element = 4 + 5 + 3 + 2 + 9 + 5 + 6 + 2 + 1 + 5 + 3 + 5 = 50

Using Matrix Traversal – O(n * m) Time and O(1) Space

The idea is to traverse every element of the matrix and keep adding them to a running sum.. This direct approach works efficiently as we must visit all elements anyway to compute the sum.

  • Initialize a variable to store the total sum
  • Traverse each row and column of the matrix using nested loops
  • Add every element to the sum while traversing

Output
50
Comment
Article Tags:
Article Tags: