fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. void addArrays(int a[], int aSize, int b[], int bSize, int sum[], int &sumSize) {
  6. int carry = 0;
  7. int i = 1, j = 1, k = 1;
  8.  
  9. // Loop through both arrays from least significant to most significant digit
  10. while (i <= aSize || j <= bSize || carry) {
  11. int digitA = (i <= aSize) ? a[i] : 0;
  12. int digitB = (j <= bSize) ? b[j] : 0;
  13.  
  14. int total = digitA + digitB + carry;
  15. carry = total / 10;
  16. sum[k++] = total % 10;
  17.  
  18. i++;
  19. j++;
  20. }
  21.  
  22. sumSize = k - 1; // Size of the resulting sum array
  23. }
  24.  
  25. int main() {
  26. int v[100], x[100], rez[200];
  27. int n, m, rezSize;
  28.  
  29. cout << "Enter size and elements for the first array:" << endl;
  30. cin >> n;
  31. for (int i = n; i >= 1; --i) {
  32. cin >> v[i];
  33. }
  34. v[0] = n; // Store the size at the beginning of the array
  35.  
  36. cout << "Enter size and elements for the second array:" << endl;
  37. cin >> m;
  38. for (int j = m; j >= 1; --j) {
  39. cin >> x[j];
  40. }
  41. x[0] = m; // Store the size at the beginning of the array
  42.  
  43. // Call the addArrays function
  44. addArrays(v, v[0], x, x[0], rez, rezSize);
  45.  
  46. // Print the result
  47. cout << "sum[] = {";
  48. for (int i = rezSize; i >= 1; --i) {
  49. cout << rez[i];
  50. if (i > 1) {
  51. cout << ", ";
  52. }
  53. }
  54. cout << "}" << endl;
  55.  
  56. return 0;
  57. }
Success #stdin #stdout 0.01s 5272KB
stdin
5 6
1 2 2 5 8
2 2 2 6 7 8
stdout
Enter size and elements for the first array:
Enter size and elements for the second array:
sum[] = {-1, -6, -7, -8, -2, -7, -1, -7, -6, -9, 4}