Add two numbers represented by two arrays in C Program

CServer Side ProgrammingProgramming

A number represented by the array is stored in such a form that each digit of the number is represented by an element of the array. For example,

Number 234 in array is {2,3,4}.

To add to such numbers we will first add number at the least significant digit and if the sum is greater than 10 propagate the carry. After this, we will go for the next consecutive digits of the array doing the same procedure and finding the sum.

Let’s take an example to add two numbers −

a = {2,9, 6}
b = {6, 3, 8}
Output: 934

Explanation − We will add the least significant digit of the number i.e. 6+8 = 14 that will propagate a carry and then for the same 9+3+1 = 13 that will again propagate the carry to next. The next will sum will be 2+6+1 = 9. This will make the sum = 934.

Algorithm

In order to find the sum of numbers stored as array. We will first check if any number has more number of digits. If yes then we will find the sum till the digits of smaller number and then go for add digits of larger number.

In addition, we will check a carry number that will keep track of the carry that may arise in the sum and needs to be forwarded, initially it will be zero and also made zero before every sum iteration. We will one by one find the sum of numbers and store it into array and then print it.

Example

 Live Demo

#include <iostream>
using namespace std;
int Sum(int a[], int b[], int n, int m){
   int sum[n];
   int i = n - 1, j = m - 1, k = n - 1;
   int c = 0, s = 0;
   while (j >= 0) {
      s = a[i] + b[j] + c;
      sum[k] = (s % 10);
      c = s / 10;
      k--;
      i--;
      j--;
   }
   while (i >= 0) {
      s = a[i] + c;
      sum[k] = (s % 10);
      c = s / 10;
      i--;
      k--;
   }
   for (int i = 0; i <= n-1; i++) {
      cout<<sum[i];
   }
}
int main(){
   int a[] = { 5, 6, 9 };
   int b[] = { 3, 8 };
   int n = sizeof(a) / sizeof(a[0]);
   int m = sizeof(b) / sizeof(b[0]);
   cout<<"The sum is ";
   if (n >= m)
      Sum(a, b, n, m);
   else
      Sum(b, a, m, n);
   return 0;
}

Output

The sum is 607
raja
Published on 19-Sep-2019 08:13:32
Advertisements