Digits of element wise sum of two arrays into a new array in C++ Program


In this tutorial, we are going to write a program that finds the sun of two array elements and store them into a separate array.

We have given two arrays and we need to add the corresponding index elements from the two arrays. If the sum is not single digits, then extract the digits from the number and store them in the new array.

Let's see an example.

Input

arr_one = {1, 2, 32, 4, 5}
arr_two = {1, 52, 3}

Output

2 5 4 3 5 4 5

Let's see the steps to solve the problem.

  • Initialize two arrays with dummy data.

  • We are using the vector to store the result as we don't know about the size of the new array.

  • Iterate through the two arrays until the index is less than the first and second array length.

  • Add the corresponding index elements from the array and store them in a new array.

  • After the completion of the above iteration. Iterate through the two arrays separately for the remaining elements.

  • Print the elements from the vector.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void pushDigits(int num, vector<int> &result) {
   if (num > 0) {
      pushDigits(num / 10, result);
      result.push_back(num % 10);
   }
}
void printVector(vector<int> &result) {
   for (int i : result) {
      cout << i << " ";
   }
   cout << endl;
}
void addTwoArrayElements(vector<int> arr_one, vector<int> arr_two) {
   vector<int> result;
   int arr_one_length = arr_one.size(), arr_two_length = arr_two.size();
   int i = 0;
   while (i < arr_one_length && i < arr_two_length) {
      pushDigits(arr_one[i] + arr_two[i], result);
      i++;
   }
   while (i < arr_one_length) {
      pushDigits(arr_one[i++], result);
   }
   while (i < arr_two_length) {
      pushDigits(arr_two[i++], result);
   }
   printVector(result);
}
int main() {
   vector<int> arr_one = {1, 2, 32, 4, 5};
   vector<int> arr_two = {1, 52, 3};
   addTwoArrayElements(arr_one, arr_two);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

2 5 4 3 5 4 5

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 27-Jan-2021

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements