Program to find sum of elements in a given 2D array
Last Updated :
29 Mar, 2023
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>
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
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 :
- Define a function named sum that takes a 2D array of integers as input and returns an integer value.
- 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].
- 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.
- Declare an integer variable sum and initialize it to zero.
- Using a loop that iterates over the elements of the 2D array, add each element to sum by dereferencing the pointer p.
- 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));
}
}
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.
Similar Reads
Program to print Sum of even and odd elements in an array Prerequisite - Array Basics Given an array, write a program to find the sum of values of even and odd index positions separately. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6} Output :Even index positions sum 9 Odd index positions sum 12 Explanation: Here, n = 6 so there will be 3 even index position
13 min read
Find the sum of all possible pairs in an array of N elements Given an array arr[] of N integers, the task is to find the sum of all the pairs possible from the given array. Note that, (arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs.Examples: Input: arr[] = {1, 2} Output: 12 All va
7 min read
Find array elements equal to sum of any subarray of at least size 2 Given an array arr[], the task is to find the elements from the array which are equal to the sum of any sub-array of size greater than 1.Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Output: 3, 5, 6 Explanation: The elements 3, 5, 6 are equal to sum of subarrays {1, 2},{2, 3} and {1, 2, 3} respectivel
6 min read
Construct sum-array with sum of elements in given range You are given an array of n-elements and an odd-integer m. You have to construct a new sum_array from given array such that sum_array[i] = ?arr[j] for (i-(m/2)) < j (i+(m/2)). note : for 0 > j or j >= n take arr[j] = 0. Examples: Input : arr[] = {1, 2, 3, 4, 5}, m = 3 Output : sum_array = {
7 min read
Sum of array elements which are multiples of a given number Given an array arr[] consisting of positive integers and an integer N, the task is to find the sum of all array elements which are multiples of N Examples: Input: arr[] = {1, 2, 3, 5, 6}, N = 3Output: 9Explanation: From the given array, 3 and 6 are multiples of 3. Therefore, sum = 3 + 6 = 9. Input:
5 min read
Sum of alternate elements of a N x N matrix Given an NxN matrix. The task is to find the sum of the alternate elements of the given matrix. For example, in a 2 x 2 matrix the alternate elements are { A[0][0], A[1, 1] } and { A[1][0], A[0][1] }. Examples: Input: mat[][] = { { 1, 2}, { 3, 4} } Output : Sum of alternate elements : 5, 5 Explanati
5 min read
2 Sum - Count Pairs with given Sum in Sorted Array Given a sorted array arr[] and an integer target, the task is to find the number of pairs in the array whose sum is equal to target.Examples: Input: arr[] = [-1, 1, 5, 5, 7], target = 6Output: 3Explanation: Pairs with sum 6 are (1, 5), (1, 5) and (-1, 7). Input: arr[] = [1, 1, 1, 1], target = 2Outpu
9 min read
Find all pairs with a given sum in two unsorted arrays Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to a given value X.Examples: Input: arr1[] = {-1, -2, 4, -6, 5, 7}, arr2[] = {6, 3, 4, 0} , x = 8Output: 4 4 5 3Input: arr1[] = {1, 2, 4, 5, 7}, arr2[] = {5, 6, 3, 4, 8}, x = 9Output: 1
13 min read
Check if is possible to get given sum from a given set of elements Given array of numbers and a integer x. Find whether it is possible or not to get x by adding elements of given array, we may pick a single element multiple times. For a given array, there can be many sum queries. Examples: Input : arr[] = { 2, 3} q[] = {8, 7} Output : Yes Yes Explanation : 2 + 2 +
7 min read