Advertisement
fahimkamal63

Sum of array

Apr 19th, 2019
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int main(){
  5.     int t; cin >> t;
  6.     while(t--){
  7.         int n, m; cin >> n >> m;
  8.         int num1[n], num2[m], i, k = n + m, result[k] = {0};
  9.         //  Taking input of both array
  10.         for(i = 0; i < n; i++) cin >> num1[i];
  11.         for(i = 0; i < m; i++) cin >> num2[i];
  12.  
  13.         int cary = 0, j;
  14.         k = 0;
  15.         i = n-1, j = m-1;
  16.         while(i > -1 && j > -1){
  17.             int temp = num1[i--] + num2[j--] + cary;
  18.             result[k++] = temp % 10;
  19.             cary = temp / 10;
  20.         }
  21.  
  22.         while(i > -1){
  23.             cary = cary + num1[i--];
  24.             result[k++] = cary % 10;
  25.             cary /= 10;
  26.         }
  27.         while(j > -1){
  28.             cary = cary + num2[j--];
  29.             result[k++] = cary % 10;
  30.             cary /= 10;
  31.         }
  32.         while(cary){
  33.             result[k++] = cary % 10;
  34.             cary /= 10;
  35.         }
  36.         for(i = k-1; i > -1; i--){
  37.             cout << result[i] << ' ';
  38.         }
  39.         cout << endl;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement