Add two numbers represented by two arrays in C++
The array stores a number in such a way that each digit of the number is represented by an array element. As an example,
The array number 147 is 1,4,7.
To add to such numbers, we will first add the number at the least significant digit and then propagate the carry if the sum is greater than 10. Following that, we will proceed to the next consecutive digits of the array, repeating the procedure and calculating the sum.
Let's say you want to add two numbers.
a = {1,2,3,4}
b = {4,3,2,6}
Now the numbers are a=1234 and b=4326. Therefore, sum of 1234 and 4326 gives 5560 as the output.
5560 is the output.
Explanation: We will add the most least significant digit of the number, i.e., 4+6 = 10, to propagate a carry, and then 3+2+1 = 6 will be the next sum. This makes the total 5560.
Algorithm
To find the sum of any numbers stored in an array. We'll start by seeing if any number has more digits than others. If yes, we will find the sum up to the digits of the smaller number and then add the digits of the larger number. Along with this, we keep on checking a carry number that will keep track of any carry that may occur in the sum and that requires to be forwarded; it will be zero at first and will be reset to zero before each sum iteration. We will find the sum of the numbers one by one, store it in an array, and then print it.
Example 1:
#include <iostream>
using namespace std;
int Sum(int a[], int b[], int s1, int s2){
int sum[s1];
int i = s1 - 1, j = s2 - 1, k = s1 - 1;
int ca = 0, s = 0;
while (j >= 0) {
s = a[i] + b[j] + ca;
sum[k] = (s % 10);
ca = s / 10;
k--;
i--;
j--;
}
while (i >= 0) {
s = a[i] + ca;
sum[k] = (s % 10);
ca = s / 10;
i--;
k--;
}
for (int i = 0; i <= s1-1; i++) {
cout<<sum[i];
}
}
int main(){
int a[] = { 5, 6, 9 };
int b[] = { 3, 8 };
int s1 = sizeof(a) / sizeof(a[0]);
int s2 = sizeof(b) / sizeof(b[0]);
cout<<"The sum of the numbers is ";
if (s1 >= s2)
Sum(a, b, s1, s2);
else
Sum(b, a, s2, s1);
return 0;
}
Output:
The sum of the two numbers is 607
Example 2:
#include <iostream>
using namespace std;
int Sum(int a[], int b[], int s1, int s2){
int sum[s1];
int i = s1 - 1, j = s2 - 1, k = s1 - 1;
int ca = 0, s = 0;
while (j >= 0) {
s = a[i] + b[j] + ca;
sum[k] = (s % 10);
ca = s / 10;
k--;
i--;
j--;
}
while (i >= 0) {
s = a[i] + ca;
sum[k] = (s % 10);
ca = s / 10;
i--;
k--;
}
for (int i = 0; i <= s1-1; i++) {
cout<<sum[i];
}
}
int main(){
int a[] = { 1, 2, 3 };
int b[] = { 3, 2, 1 };
int s1 = sizeof(a) / sizeof(a[0]);
int s2 = sizeof(b) / sizeof(b[0]);
cout<<"The sum of the numbers is ";
if (s1 >= s2)
Sum(a, b, s1, s2);
else
Sum(b, a, s2, s1);
return 0;
}
Output:
The sum of the two numbers is 444