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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read