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 = 21input: 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.
- Use a nested loop to traverse the columns of the matrix for each row.
- 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++
|
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)
order accutane 40mg online cheap purchase isotretinoin online buy azithromycin
ventolin cheap buy augmentin buy augmentin 1000mg sale
modafinil 100mg tablet modafinil 100mg cheap metoprolol without prescription
avodart 0.5mg pill xenical 60mg over the counter orlistat uk