ADD TWO ARRAY

 avatar
user_6075971
plain_text
2 years ago
1.7 kB
0
Indexable
Never
#include <iostream>
#include <vector>
using namespace std;

//************ADD TWO ARRAY
void add_array(int arr1[], int arr2[], int m, int n)
{
    vector<int> v;
    int a = n - 1;
    int b = m - 1;
    int carry = 0;
    while (a >= 0 && b >= 0)
    {
        int sum = arr1[a] + arr2[b] + carry;
        carry = sum / 10;
        int ans = sum % 10;
        v.push_back(ans);
        a--;
        b--;
    }
    while (a >= 0)
    {
        int sum = arr1[a] + carry;
        carry = sum / 10;
        int ans = sum % 10;
        v.push_back(ans);
        a--;
    }
    while (b >= 0)
    {
        int sum = arr2[b] + carry;
        carry = sum / 10;
        int ans = sum % 10;
        v.push_back(ans);
        b--;
    }
    while (carry != 0)
    {
        int sum = carry;
        carry = sum / 10;
        int ans = sum % 10;
        v.push_back(ans);
    }
    int s = 0;
    int e = v.size()-1;
    while (s <= e)
    {
        swap(v[s], v[e]);
        s++;
        e--;
    }
    for (auto value : v)
    {
        cout <<"FINAL RESULT" <<value << " ";
    }
}
void input(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
}
void print(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    }
}

int main()
{
    int n, m;

    cout << "ENTER THE FIRST ARRAY SIZE--->";
    cin >> n;
    cout << "ENTER THE SECOND ARRAY SIZE--->";
    cin >> m;
    int arr1[n];
    int arr2[m];
    cout << "ENTER THE FIRST ARRAY ELEMENT" << endl;

    input(arr1, n);
    print(arr1, n);
    cout << endl;
    cout << "ENTER THE SECOND ARRAY ELEMENT" << endl;
    input(arr2, m);
    print(arr2, m);
    cout << endl;
    add_array(arr1, arr2, m, n);

    return 0;
}