Open In App

Program to find sum of elements in a given 2D array

Last Updated : 29 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D array of order M * N, the task is to find out the sum of elements of the matrix.

Examples:

Input: array[2][2] = {{1, 2}, {3, 4}};
Output: 10

Input: array[4][4] = {{1, 2, 3, 4}, 
                                 {5, 6, 7, 8}, 
                                 {9, 10, 11, 12}, 
                                 {13, 14, 15, 16}};
Output: 136

 

Approach:

The sum of each element of the 2D array can be calculated by traversing through the matrix and adding up the elements.

Below is the implement the above approach-

C++




// C++ program to find sum of
// elements in 2D array
#include <iostream>
using namespace std;
 
// Get the size m and n
#define M 4
#define N 4
 
// Function to calculate sum
// of elements in 2d array
int sum(int arr[M][N])
{
    int i, j;
    int sum = 0;
 
    // Finding the sum
    for (i = 0; i < M; ++i) {
        for (j = 0; j < N; ++j) {
            // Add the element
            sum = sum + arr[i][j];
        }
    }
    return sum;
}
 
// Driver code
int main()
{
    int i, j;
    int arr[M][N];
 
    // Get the matrix elements
    int x = 1;
    for (i = 0; i < M; i++)
        for (j = 0; j < N; j++)
            arr[i][j] = x++;
 
    // Get sum
    cout << sum(arr);
    return 0;
}


Java




// Java code for the above approach
import java.io.*;
 
class GFG {
  // Get the size m and n
  static int M = 4;
  static int N = 4;
 
  // Function to calculate sum
  // of elements in 2d array
  static int sum(int arr[][])
  {
    int i, j;
    int sum = 0;
 
    // Finding the sum
    for (i = 0; i < M; ++i) {
      for (j = 0; j < N; ++j) {
        // Add the element
        sum = sum + arr[i][j];
      }
    }
    return sum;
  }
 
  public static void main (String[] args)
  {
    int i, j;
    int arr[][]= new int[M][N];
 
    // Get the matrix elements
    int x = 1;
    for (i = 0; i < M; i++)
      for (j = 0; j < N; j++)
        arr[i][j] = x++;
 
    // Get sum
    System.out.println(sum(arr));
  }
}
 
// This code is contributed by Potta Lokesh


Python3




# python program to find sum of
# elements in 2D array
 
# Get the size m and n
M = 4
N = 4
 
# Function to calculate sum
# of elements in 2d array
def sum(arr):
 
    sum = 0
 
    # Finding the sum
    for i in range(M):
        for j in range(N):
           
            # Add the element
            sum = sum + arr[i][j]
 
    return sum
 
# Driver code
arr = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
 
# Get the matrix elements
x = 1
for i in range(M):
    for j in range(N):
        arr[i][j] = x
        x += 1
 
# Get sum
print(sum(arr))
 
# This code is contributed by ninja_hattori


C#




using System;
 
class GFG
{
 
  // Get the size m and n
  static int M = 4;
  static int N = 4;
 
  // Function to calculate sum
  // of elements in 2d array
  static int sum(int [,]arr)
  {
    int i, j;
    int sum = 0;
 
    // Finding the sum
    for (i = 0; i < M; ++i)
    {
      for (j = 0; j < N; ++j)
      {
 
        // Add the element
        sum = sum + arr[i,j];
      }
    }
    return sum;
  }
 
  static public void Main (String[] args){
    int i, j;
    int [,]arr= new int[M,N];
 
    // Get the matrix elements
    int x = 1;
    for (i = 0; i < M; i++)
      for (j = 0; j < N; j++)
        arr[i,j] = x++;
 
    // Get sum
    Console.WriteLine(sum(arr));
    // Code
  }
}
// This code is contributed by Kritima Gupta


Javascript




    <script>
        // JavaScript program to find sum of
        // elements in 2D array
 
        // Get the size m and n
        const M = 4;
        const N = 4;
 
        // Function to calculate sum
        // of elements in 2d array
        const sum = (arr) => {
            let i, j;
            let sum = 0;
 
            // Finding the sum
            for (i = 0; i < M; ++i) {
                for (j = 0; j < N; ++j) {
                    // Add the element
                    sum = sum + arr[i][j];
                }
            }
            return sum;
        }
 
        // Driver code
 
        let i, j;
        let arr = new Array(M).fill(0).map(() => new Array(N).fill(0));
 
        // Get the matrix elements
        let x = 1;
        for (i = 0; i < M; i++)
            for (j = 0; j < N; j++)
                arr[i][j] = x++;
 
        // Get sum
        document.write(sum(arr));
 
// This code is contributed by rakeshsahni.
    </script>


Output

136

 
Time Complexity: O(M*N) 
Auxiliary Space: O(1)

Another Method: Using STL. Calling the inbuilt function for sum of elements of an array in STL. We use accumulate( first, last, sum) function to return the sum of 1D array.

Below is the implementation of idea.

C++




// C++ program to find sum of
// elements in 2D array
#include <iostream>
#include <numeric>
using namespace std;
 
// Get the size m and n
#define M 4
#define N 4
 
// Function to calculate sum
// of elements in 2d array
int sum(int arr[M][N])
{
    int i, j;
    int sum = 0;
 
    // Finding the sum
    for (i = 0; i < M; ++i) {
        int ans = 0;
        sum += accumulate(arr[i], arr[i] + N, ans);
    }
    return sum;
}
 
// Driver code
int main()
{
    int i, j;
    int arr[M][N];
 
    // Get the matrix elements
    int x = 1;
    for (i = 0; i < M; i++)
        for (j = 0; j < N; j++)
            arr[i][j] = x++;
 
    // Get sum
    cout << sum(arr);
    return 0;
}


Python




# python program to find sum of
# elements in 2D array
 
# Get the size m and n
M = 4
N = 4
 
# Function to calculate sum
# of elements in 2d array
 
 
def Findsum(arr):
 
    ans = 0
 
    # Finding the sum
    for i in range(M):
        ans += int(sum(arr[i]))
 
    return ans
 
 
# Driver code
arr = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
 
# Get the matrix elements
x = 1
for i in range(M):
    for j in range(N):
        arr[i][j] = x
        x += 1
 
# Get sum
print(Findsum(arr))
 
# This code is contributed by Sam_snehil


Javascript




// JavaScript program to find sum of
        // elements in 2D array
 
        // Get the size m and n
        const M = 4;
        const N = 4;
 
        // Function to calculate sum
        // of elements in 2d array
        const sum = (arr) => {
            let i, j;
            let sum = 0;
 
            // Finding the sum
            for (i = 0; i < M; ++i) {
                    sum = sum + arr[i].reduce(function(accumulator, currentValue){ return accumulator + currentValue;}, 0);
                 
            }
            return sum;
        }
 
        // Driver code
 
        let i, j;
        let arr = new Array(M).fill(0).map(() => new Array(N).fill(0));
 
        // Get the matrix elements
        let x = 1;
        for (i = 0; i < M; i++)
            for (j = 0; j < N; j++)
                arr[i][j] = x++;
 
        // Get sum
        document.write(sum(arr));
 
// This code is contributed by rakeshsahni.


Java




public class SumOf2DArray {
    // Function to calculate sum of elements in 2d array
    public static int Findsum(int[][] arr) {
        int ans = 0;
        int M = arr.length;
        int N = arr[0].length;
 
        // Finding the sum
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                ans += arr[i][j];
            }
        }
 
        return ans;
    }
 
    public static void main(String args[]) {
        // Get the size m and n
        int M = 4;
        int N = 4;
        int x = 1;
        int[][] arr = new int[M][N];
 
        // Get the matrix elements
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                arr[i][j] = x;
                x++;
            }
        }
 
        // Get sum
        System.out.println(Findsum(arr));
    }
}


C#




// C# code for the above approach
 
using System;
 
public class GFG {
 
    // Function to calculate sum of elements in 2d array
    static int Findsum(int[, ] arr)
    {
        int ans = 0;
        int M = arr.GetLength(0);
        int N = arr.GetLength(1);
 
        // Finding the sum
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                ans += arr[i, j];
            }
        }
 
        return ans;
    }
 
    static public void Main()
    {
 
        // Code
        // Get the size m and n
        int M = 4;
        int N = 4;
        int x = 1;
        int[, ] arr = new int[M, N];
 
        // Get the matrix elements
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                arr[i, j] = x;
                x++;
            }
        }
 
        // Get sum
        Console.WriteLine(Findsum(arr));
    }
}
 
// This code is contributed by lokeshmvs21


Output

136

Time Complexity: O(n*m) (where n = no. of rows and m = no. of column)

Auxiliary Space: O(1)

Another Approach : Using pointers
We can also use pointers to find the sum of elements in a 2D array. We can use a pointer to point to the first element of the array and iterate through each element in the array by incrementing the pointer.

Step by Step algorithm :

  1. Define a function named sum that takes a 2D array of integers as input and returns an integer value.
  2. In the sum function, declare a pointer ptr of type integer and assign it the address of the first element of the 2D array using &arr[0][0].
  3. Declare another pointer end of type integer and assign it the address of the element one beyond the last element of the 2D array, by adding 1 to the address of the last element of the array &arr[M-1][N-1]. This way we can make imaginary indexes.
  4. Declare an integer variable sum and initialize it to zero.
  5. Using a loop that iterates over the elements of the 2D array, add each element to sum by dereferencing the pointer p.
  6. Return the sum value.

C++




#include <iostream>
#include <numeric>
using namespace std;
 
// Get the size m and n
#define M 4
#define N 4
 
// Function to calculate sum
// of elements in 2d array
int sum(int arr[M][N])
{
    int* ptr = &arr[0][0];
    int* end = &arr[M-1][N-1] + 1; // Pointer to one element beyond the end of the array
    int sum = 0;
 
    // Iterate through the array using a pointer
    for (int* p = ptr; p != end; p++) {
        sum += *p;
    }
 
    return sum;
}
 
// Driver code
int main()
{
    int i, j;
    int arr[M][N];
 
    // Get the matrix elements
    int x = 1;
    for (i = 0; i < M; i++)
        for (j = 0; j < N; j++)
            arr[i][j] = x++;
 
    // Get sum
    cout << sum(arr) << endl;
    return 0;
}


Python3




# Get the size m and n
M = 4
N = 4
 
# Function to calculate sum of elements in 2d array
def sum(arr):
    s = 0
    for i in range(M):
        for j in range(N):
            s += arr[i][j]
    return s
 
# Driver code
if __name__ == '__main__':
    arr = [[0 for j in range(N)] for i in range(M)]
 
    # Get the matrix elements
    x = 1
    for i in range(M):
        for j in range(N):
            arr[i][j] = x
            x += 1
 
    # Get sum
    print(sum(arr))


C#




using System;
 
class Program
{
    // Get the size m and n
    const int M = 4;
    const int N = 4;
 
    // Function to calculate sum
    // of elements in 2d array
    static int Sum(int[,] arr)
    {
        int sum = 0;
 
        // Iterate through the array using two nested loops
        for (int i = 0; i < M; i++)
        {
            for (int j = 0; j < N; j++)
            {
                sum += arr[i, j];
            }
        }
 
        return sum;
    }
 
    // Driver code
    static void Main(string[] args)
    {
        int[,] arr = new int[M, N];
 
        // Get the matrix elements
        int x = 1;
        for (int i = 0; i < M; i++)
        {
            for (int j = 0; j < N; j++)
            {
                arr[i, j] = x++;
            }
        }
 
        // Get sum
        Console.WriteLine(Sum(arr));
    }
}


Javascript




// Javascript code addition
 
// Get the size m and n
let M = 4;
let N = 4;
 
// Function to calculate sum of elements in 2d array
function sum(arr){
    let s = 0;
    for(let i = 0; i < M; i++){
        for(let j = 0; j < N; j++){
            s += arr[i][j];
        }
    }
    return s;
}
 
// Driver code
let arr = new Array(N);
for(let i = 0; i < N; i++){
    arr[i] = new Array(M).fill(0);
}
 
// Get the matrix elements
let x = 1;
for(let i = 0; i < M; i++){
    for(let j = 0; j < N; j++){
        arr[i][j] = x;
        x += 1;
    }
}
 
// Get sum
console.log(sum(arr));
 
// The code is contributed by Arushi Jindal.


Java




/*package whatever //do not write package name here */
 
import java.util.*;
 
public class GFG {
    // Get the size m and n
    private static final int M = 4;
    private static final int N = 4;
 
    // Function to calculate sum
    // of elements in 2d array
    private static int sum(int[][] arr) {
        int[] ptr = arr[0];
        int[] end = arr[M - 1];
        int sum = 0;
 
        // Iterate through the array using a pointer
        for (int[] row : arr) {
            for (int val : row) {
                sum += val;
            }
        }
 
        return sum;
    }
 
    // Driver code
    public static void main(String[] args) {
        int[][] arr = new int[M][N];
 
        // Get the matrix elements
        int x = 1;
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                arr[i][j] = x++;
            }
        }
 
        // Get sum
        System.out.println(sum(arr));
    }
}


Output

136

Time Complexity: O(M*N) 

This is because the function sum() iterates through each element of the matrix using a pointer, taking O(M*N) time.

Auxiliary Space: O(1)

This is because the function sum() uses a constant amount of extra space for the pointers and the sum variable, taking O(1) space.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads