Add two numbers represented by two arrays

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
    }
}
  
// This article is contributed by Gitanjali.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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".

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.
?>

chevron_right



Output :

1000


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : gautamkumar, vt_m, SonamKumari



Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.