# Add elements of given arrays with given constraints?

CServer Side ProgrammingProgramming

Here we will see one problem. We will add two array elements and store them into another array. But we will follow some constraints. These constraints are like below −

• Addition should be stated from 0th index of both of the array
• Split the sum if it is more than one-digit number, and place each digit to the corresponding locations
• Remaining digits of the larger input array will be stored at output array

Let us see the algorithm to get the idea.

## Algorithm

Begin
define empty vector out
i := 0
while i is less than both arr1.length and arr2.length, do
if add is single digit number, then
else
split the digits and push each digit into out
end if
done
while arr1 is not exhausted, do
insert each element directly into out if they are single digit, otherwise split and insert
done
while arr2 is not exhausted, do
insert each element directly into out if they are single digit, otherwise split and insert
done
End

## Example

#include<iostream>
#include<vector>
using namespace std;
void splitDigit(int num, vector<int> &out) { //split the digits and store into vector to add into array
vector<int> arr;
while (num) {
arr.insert(arr.begin(), num%10);
num = num/10;
}
out.insert(out.end(), arr.begin(), arr.end());
}
void addArrayConstraints(int arr1[], int arr2[], int m, int n) {
vector<int> out;
int i = 0; //point current index of arr1 and arr2
while (i < m && i <n) {
int add = arr1[i] + arr2[i];
if (add < 10) //if it is single digit, put the sum, otherwise split them
else
i++;
}
}
while (i < m) //if arr1 has more elements
splitDigit(arr1[i++], out);
while (i < n) //if arr2 has more elements
splitDigit(arr2[i++], out);
for (int i = 0; i< out.size(); i++)
cout << out[i] << " ";
}
main() {
int arr1[] = {9323, 8, 6, 55, 25, 6};
int arr2[] = {38, 11, 4, 7, 8, 7, 6, 99};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int n2 = sizeof(arr2) / sizeof(arr2[0]);
}
9 3 6 1 1 9 1 0 6 2 3 3 1 3 6 9 9