### how to sum up two arrays together?

for example if we have array1[5]= {1,2,3,4,5}
and array2[5]={2,3,4,0,7)

how do you sum them up as 12345 + 23407 . And when i say sum I mean normal mathematical sum.

here is my code to get an idea of what i am doing

 ``123456789101112131415161718192021222324252627282930313233343536373839404142`` ``````int main () { string str1; string str2; int i, j; int size1, size2; int Num1[21]; int Num2[21]; cout <<" enter your first number: " << endl; cin >> str1; cout << endl; cout << str1 << " is your first number" << endl; cout << "enter the second number: " << endl; cin >> str2; cout << endl; cout << str2 << " is your second number" << endl; size1=str1.size(); size2=str2.size(); for(j=0;j<=size1;j++) { for (i=19; i>=0; i--) Num1[i]= str1.at(j); } for(j=0;j<=size2;j++) { for (i=19; i>=0; i--) Num2[i]= str2.at(j); } }``````
http://www.cplusplus.com/forum/general/100823/#msg542146

Simply arithmetic

If you have any questions about the code, I can help
Last edited on
As Smac89 said, it's "simply arithmatic".

You just get the code to do what you do manually: add the units, add the tens, ... with carrying, etc.

Andy

PS You might want to consider

array1[5]= {9,8,7,6,5};
array2[4]= {4,3,2,1);

array1[5]= {1,2,3,4,5}
array2[5]= {2,3,4,0,7)

so you handle different length numbers correctly.
Here's a neat way to sum two int arrays together:

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556`` ``````#include #include #include class num { public: num() : number(0), result(NULL) { } num(int* numbers, unsigned size) : number(0), result(NULL) { std::stringstream ss; for (unsigned n=0; n < size; ++n) ss << numbers[n]; ss >> number; } ~num() { delete result; } num& operator+(const num& rhs) { if (result) delete result; result = new num(); result->number = this->number + rhs.number; return *result; } friend std::ostream& operator<<(std::ostream& os, const num& n) { os << n.number; return os; } private: int number; num* result; }; int main(int argc, char* argv[]) { int a1[] = {9,8,7,6,5}; int a2[] = {4,3,2,1}; num a(a1, sizeof(a1)/sizeof(int)), b(a2, sizeof(a2)/sizeof(int)); num result = a + b; std::cout << a << '+' << b << '=' << result << std::endl; return 0; }``````

HTH
> for example if we have array1[5]= {1,2,3,4,5}
> and array2[5]={2,3,4,0,7)
> how do you sum them up as 12345 + 23407 .
> And when i say sum I mean normal mathematical sum.

 ``12345678910111213141516171819`` ``````#include #include int main() { constexpr int N = 5 ; constexpr int a[N] = { 1, 2, 3, 4, 5 } ; constexpr int b[N] = { 2, 9, 8, 0, 7 } ; const auto isdigit = [] ( int v ) { return v >= 0 && v < 10 ; } ; int sum = 0 ; for( int i = 0 ; i < N ; ++i ) { assert( isdigit( a[i] ) && isdigit( b[i] ) ) ; sum *= 10 ; sum += a[i] + b[i] ; } std::cout << sum << '\n' ; }``````

http://ideone.com/J4qEc9
Topic archived. No new replies allowed.