Add two numbers represented by two arrays
Last Updated :
14 Oct, 2023
Given two array A[0....n-1] and B[0....m-1] of size n and m respectively, representing two numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3} and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of both the number. In above case, answer is 337.
Examples :
Input : n = 3, m = 3
a[] = { 1, 2, 3 }
b[] = { 2, 1, 4 }
Output : 337
123 + 214 = 337
Input : n = 4, m = 3
a[] = { 9, 5, 4, 9 }
b[] = { 2, 1, 4 }
Output : 9763
The idea is to start traversing both the array simultaneously from the end until we reach the 0th index of either of the array. While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum. While adding 0th index element if the carry left, then append it to beginning of the number.
Below is the illustration of approach:

Below is the implementation of this approach:
C++
// CPP program to sum two numbers represented two
// arrays.
#include <bits/stdc++.h>
using namespace std;
// Return sum of two number represented by the arrays.
// Size of a[] is greater than b[]. It is made sure
// be the wrapper function
int calSumUtil(int a[], int b[], int n, int m)
{
// array to store sum.
int sum[n];
int i = n - 1, j = m - 1, k = n - 1;
int carry = 0, s = 0;
// Until we reach beginning of array.
// we are comparing only for second array
// because we have already compare the size
// of array in wrapper function.
while (j >= 0) {
// find sum of corresponding element
// of both arrays.
s = a[i] + b[j] + carry;
sum[k] = (s % 10);
// Finding carry for next sum.
carry = s / 10;
k--;
i--;
j--;
}
// If second array size is less the first
// array size.
while (i >= 0) {
// Add carry to first array elements.
s = a[i] + carry;
sum[k] = (s % 10);
carry = s / 10;
i--;
k--;
}
int ans = 0;
// If there is carry on adding 0 index elements.
// append 1 to total sum.
if (carry)
ans = 10;
// Converting array into number.
for (int i = 0; i <= n - 1; i++) {
ans += sum[i];
ans *= 10;
}
return ans / 10;
}
// Wrapper Function
int calSum(int a[], int b[], int n, int m)
{
// Making first array which have
// greater number of element
if (n >= m)
return calSumUtil(a, b, n, m);
else
return calSumUtil(b, a, m, n);
}
// Driven Program
int main()
{
int a[] = { 9, 3, 9 };
int b[] = { 6, 1 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
cout << calSum(a, b, n, m) << endl;
return 0;
}
Java
// Java program to sum two numbers
// represented two arrays.
import java.io.*;
class GFG {
// Return sum of two number represented by
// the arrays. Size of a[] is greater than
// b[]. It is made sure be the wrapper
// function
static int calSumUtil(int a[], int b[],
int n, int m)
{
// array to store sum.
int[] sum= new int[n];
int i = n - 1, j = m - 1, k = n - 1;
int carry = 0, s = 0;
// Until we reach beginning of array.
// we are comparing only for second
// array because we have already compare
// the size of array in wrapper function.
while (j >= 0)
{
// find sum of corresponding element
// of both array.
s = a[i] + b[j] + carry;
sum[k] = (s % 10);
// Finding carry for next sum.
carry = s / 10;
k--;
i--;
j--;
}
// If second array size is less
// the first array size.
while (i >= 0)
{
// Add carry to first array elements.
s = a[i] + carry;
sum[k] = (s % 10);
carry = s / 10;
i--;
k--;
}
int ans = 0;
// If there is carry on adding 0 index
// elements append 1 to total sum.
if (carry == 1)
ans = 10;
// Converting array into number.
for ( i = 0; i <= n - 1; i++) {
ans += sum[i];
ans *= 10;
}
return ans / 10;
}
// Wrapper Function
static int calSum(int a[], int b[], int n,
int m)
{
// Making first array which have
// greater number of element
if (n >= m)
return calSumUtil(a, b, n, m);
else
return calSumUtil(b, a, m, n);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int a[] = { 9, 3, 9 };
int b[] = { 6, 1 };
int n = a.length;
int m = b.length;
System.out.println(calSum(a, b, n, m));
}
}
//
Python3
# Python3 code to sum two numbers
# representer two arrays.
# Return sum of two number represented
# by the arrays. Size of a[] is greater
# than b[]. It is made sure be the
# wrapper function
def calSumUtil( a , b , n , m ):
# array to store sum.
sum = [0] * n
i = n - 1
j = m - 1
k = n - 1
carry = 0
s = 0
# Until we reach beginning of array.
# we are comparing only for second array
# because we have already compare the size
# of array in wrapper function.
while j >= 0:
# find sum of corresponding element
# of both array.
s = a[i] + b[j] + carry
sum[k] = (s % 10)
# Finding carry for next sum.
carry = s // 10
k-=1
i-=1
j-=1
# If second array size is less the first
# array size.
while i >= 0:
# Add carry to first array elements.
s = a[i] + carry
sum[k] = (s % 10)
carry = s // 10
i-=1
k-=1
ans = 0
# If there is carry on adding 0 index elements.
# append 1 to total sum.
if carry:
ans = 10
# Converting array into number.
for i in range(n):
ans += sum[i]
ans *= 10
return ans // 10
# Wrapper Function
def calSum(a, b, n, m ):
# Making first array which have
# greater number of element
if n >= m:
return calSumUtil(a, b, n, m)
else:
return calSumUtil(b, a, m, n)
# Driven Code
a = [ 9, 3, 9 ]
b = [ 6, 1 ]
n = len(a)
m = len(b)
print(calSum(a, b, n, m))
# This code is contributed by "Sharad_Bhardwaj".
C#
// C# program to sum two numbers
// represented two arrays.
using System;
class GFG {
// Return sum of two number represented by
// the arrays. Size of a[] is greater than
// b[]. It is made sure be the wrapper
// function
static int calSumUtil(int []a, int []b,
int n, int m)
{
// array to store sum.
int[] sum= new int[n];
int i = n - 1, j = m - 1, k = n - 1;
int carry = 0, s = 0;
// Until we reach beginning of array.
// we are comparing only for second
// array because we have already compare
// the size of array in wrapper function.
while (j >= 0)
{
// find sum of corresponding element
// of both array.
s = a[i] + b[j] + carry;
sum[k] = (s % 10);
// Finding carry for next sum.
carry = s / 10;
k--;
i--;
j--;
}
// If second array size is less
// the first array size.
while (i >= 0)
{
// Add carry to first array elements.
s = a[i] + carry;
sum[k] = (s % 10);
carry = s / 10;
i--;
k--;
}
int ans = 0;
// If there is carry on adding 0 index
// elements append 1 to total sum.
if (carry == 1)
ans = 10;
// Converting array into number.
for ( i = 0; i <= n - 1; i++) {
ans += sum[i];
ans *= 10;
}
return ans / 10;
}
// Wrapper Function
static int calSum(int []a, int []b, int n,
int m)
{
// Making first array which have
// greater number of element
if (n >= m)
return calSumUtil(a, b, n, m);
else
return calSumUtil(b, a, m, n);
}
// Driver program
public static void Main()
{
int []a = { 9, 3, 9 };
int []b = { 6, 1 };
int n = a.Length;
int m = b.Length;
Console.WriteLine(calSum(a, b, n, m));
}
}
// This article is contributed by vt_m.
JavaScript
<script>
// Javascript program to sum two numbers represented two
// arrays.
// Return sum of two number represented by the arrays.
// Size of a[] is greater than b[]. It is made sure
// be the wrapper function
function calSumUtil(a, b, n, m)
{
// array to store sum.
let sum = new Array(n);
let i = n - 1, j = m - 1, k = n - 1;
let carry = 0, s = 0;
// Until we reach beginning of array.
// we are comparing only for second array
// because we have already compare the size
// of array in wrapper function.
while (j >= 0) {
// find sum of corresponding element
// of both arrays.
s = a[i] + b[j] + carry;
sum[k] = (s % 10);
// Finding carry for next sum.
carry = Math.floor(s / 10);
k--;
i--;
j--;
}
// If second array size is less the first
// array size.
while (i >= 0) {
// Add carry to first array elements.
s = a[i] + carry;
sum[k] = (s % 10);
carry = Math.floor(s / 10);
i--;
k--;
}
let ans = 0;
// If there is carry on adding 0 index elements.
// append 1 to total sum.
if (carry)
ans = 10;
// Converting array into number.
for (let i = 0; i <= n - 1; i++) {
ans += sum[i];
ans *= 10;
}
return ans / 10;
}
// Wrapper Function
function calSum(a, b, n, m)
{
// Making first array which have
// greater number of element
if (n >= m)
return calSumUtil(a, b, n, m);
else
return calSumUtil(b, a, m, n);
}
// Driven Program
let a = [ 9, 3, 9 ];
let b = [ 6, 1 ];
let n = a.length;
let m = b.length;
document.write(calSum(a, b, n, m) + "<br>");
// This code is contributed by Mayank Tyagi
</script>
PHP
<?php
// PHP program to sum two numbers
// represented two arrays.
// Return sum of two number represented
// by the arrays. Size of a[] is greater
// than b[]. It is made sure be the
// wrapper function
function calSumUtil($a, $b, $n, $m)
{
// array to store sum.
$sum = array();
$i = $n - 1; $j = $m - 1; $k = $n - 1;
$carry = 0; $s = 0;
// Until we reach beginning of array.
// we are comparing only for second array
// because we have already compare the size
// of array in wrapper function.
while ($j >= 0)
{
// find sum of corresponding
// element of both array.
$s = $a[$i] + $b[$j] + $carry;
$sum[$k] = ($s % 10);
// Finding carry for next sum.
$carry = $s / 10;
$k--;
$i--;
$j--;
}
// If second array size is less
// than the first array size.
while ($i >= 0)
{
// Add carry to first array elements.
$s = $a[$i] + $carry;
$sum[$k] = ($s % 10);
$carry = $s / 10;
$i--;
$k--;
}
$ans = 0;
// If there is carry on
// adding 0 index elements.
// append 1 to total sum.
if ($carry)
$ans = 10;
// Converting array into number.
for ( $i = 0; $i <= $n - 1; $i++)
{
$ans += $sum[$i];
$ans *= 10;
}
return $ans / 10;
}
// Wrapper Function
function calSum( $a, $b, $n, $m)
{
// Making first array which have
// greater number of element
if ($n >= $m)
return calSumUtil($a, $b, $n, $m);
else
return calSumUtil($b, $a, $m, $n);
}
// Driven Code
$a = array( 9, 3, 9 );
$b = array( 6, 1 );
$n = count($a);
$m = count($b);
echo calSum($a, $b, $n, $m);
// This article is contributed by anuj_67.
?>
Time Complexity: O(n + m)
Auxiliary Space: O(max(n, m))
Approach 2: Iterative approach:
The function "addArrays" that takes two arrays of integers "arr1" and "arr2" of sizes "n" and "m" respectively.
And it returns a vector that contains the sum of the two arrays. The addition is performed digit-by-digit, starting from the rightmost digit of each arrays, and any carry is propagated to the next digit.
The implementation use a typical algorithm for digit-by-digit addition of two numbers. The corresponding digits from the two arrays are added, along with any carries from earlier additions, beginning with the rightmost digit of each array. The remainder is added to the result vector after the sum is divided by 10 to determine the carry for the following addition. The procedure is repeated until the final carry and all digits of the two arrays are added.
C++
#include <iostream>
#include <vector>
using namespace std;
vector<int> addArrays(int arr1[], int arr2[], int n, int m) {
// Initialize the result vector to store the sum
vector<int> result;
// Initialize the carry variable to 0
int carry = 0;
// Loop through the arrays from right to left
for (int i = n-1, j = m-1; i >= 0 || j >= 0 || carry > 0; i--, j--) {
// Calculate the sum of the corresponding digits in the arrays
int sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
// Calculate the carry, if any, to be added to the next sum
carry = sum / 10;
// Calculate the digit to be added to the result vector
int digit = sum % 10;
// Add the digit to the result vector
result.insert(result.begin(), digit);
}
// Return the result vector
return result;
}
int main() {
// Initialize the input arrays
int arr1[] = {9, 5, 4, 9};
int arr2[] = {2, 1, 4};
// Get the sizes of the arrays
int n = sizeof(arr1)/sizeof(arr1[0]);
int m = sizeof(arr2)/sizeof(arr2[0]);
// Calculate the sum of the arrays and store it in the result vector
vector<int> result = addArrays(arr1, arr2, n, m);
// Print the result vector
for (int i = 0; i < result.size(); i++) {
cout << result[i];
}
cout << endl;
return 0;
}
Java
import java.util.ArrayList;
public class AddArrays {
public static ArrayList<Integer> addArrays(int[] arr1, int[] arr2) {
// Initialize the result vector to store the sum
ArrayList<Integer> result = new ArrayList<>();
int n = arr1.length;
int m = arr2.length;
// Initialize the carry variable to 0
int carry = 0;
// Loop through the arrays from right to left
for (int i = n - 1, j = m - 1; i >= 0 || j >= 0 || carry > 0; i--, j--) {
// Calculate the sum of the corresponding digits in the arrays
int sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
// Calculate the carry, if any, to be added to the next sum
carry = sum / 10;
// Calculate the digit to be added to the result vector
int digit = sum % 10;
// Add the digit to the result vector
result.add(0, digit);
}
return result;
}
public static void main(String[] args) {
// Initialize the input arrays
int[] arr1 = {9, 5, 4, 9};
int[] arr2 = {2, 1, 4};
// Calculate the sum of the arrays and store it in the result vector
ArrayList<Integer> result = addArrays(arr1, arr2);
for (int num : result) {
System.out.print(num);
}
System.out.println();
}
}
Python
# code
def add_arrays(arr1, arr2):
n, m = len(arr1), len(arr2)
result = []
carry = 0
i, j = n-1, m-1
while i >= 0 or j >= 0 or carry > 0:
sum = (arr1[i] if i >= 0 else 0) + (arr2[j] if j >= 0 else 0) + carry
carry = sum // 10
digit = sum % 10
result.insert(0, digit)
i -= 1
j -= 1
return result
# Example usage
arr1 = [9, 5, 4, 9]
arr2 = [2, 1, 4]
result = add_arrays(arr1, arr2)
print(result)
C#
using System;
using System.Collections.Generic;
class Program
{
static List<int> AddArrays(int[] arr1, int[] arr2, int n, int m)
{
// Initialize the result list to store the sum
List<int> result = new List<int>();
// Initialize the carry variable to 0
int carry = 0;
// Loop through the arrays from right to left
for (int i = n - 1, j = m - 1; i >= 0 || j >= 0 || carry > 0; i--, j--)
{
// Calculate the sum of the corresponding digits in the arrays
int sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
// Calculate the carry, if any, to be added to the next sum
carry = sum / 10;
// Calculate the digit to be added to the result list
int digit = sum % 10;
// Add the digit to the result list
result.Insert(0, digit);
}
// Return the result list
return result;
}
static void Main()
{
// Initialize the input arrays
int[] arr1 = { 9, 5, 4, 9 };
int[] arr2 = { 2, 1, 4 };
// Get the sizes of the arrays
int n = arr1.Length;
int m = arr2.Length;
// Calculate the sum of the arrays and store it in the result list
List<int> result = AddArrays(arr1, arr2, n, m);
// Print the result list
foreach (int digit in result)
{
Console.Write(digit);
}
Console.WriteLine();
}
}
JavaScript
function addArrays(arr1, arr2) {
// Initialize the result array to store the sum
const result = [];
// Initialize the carry variable to 0
let carry = 0;
// Get the lengths of the input arrays
const n = arr1.length;
const m = arr2.length;
// Loop through the arrays from right to left
for (let i = n - 1, j = m - 1; i >= 0 || j >= 0 || carry > 0; i--, j--) {
// Calculate the sum of the corresponding digits in the arrays
const sum = (i >= 0 ? arr1[i] : 0) + (j >= 0 ? arr2[j] : 0) + carry;
// Calculate the carry, if any, to be added to the next sum
carry = Math.floor(sum / 10);
// Calculate the digit to be added to the result array
const digit = sum % 10;
// Add the digit to the beginning of the result array
result.unshift(digit);
}
// Return the result array
return result;
}
// Initialize the input arrays
const arr1 = [9, 5, 4, 9];
const arr2 = [2, 1, 4];
// Calculate the sum of the arrays and store it in the result array
const result = addArrays(arr1, arr2);
// Print the result array
console.log(result.join('')); // Join the digits and print
// This code is contributed by shivamgupta310570
Time Complexity: O(max(n, m))
Auxiliary Space: O(max(n, m))
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA 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
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem