# sum of 2 int arrays

• 10-21-2005
maro009
sum of 2 int arrays
if i have 2 int arays what is the best way to sum the two in new array?
• 10-21-2005
Salem
A for loop, and use of the + operator
• 10-21-2005
Code:

```#include "stdafx.h" #include <iostream> using namespace std; void print (int* a, int* b, int arraySize) {   int* aPtr;   int* bPtr;   int i;   cout << "The values:" << endl;   for (i = 0, aPtr = a, bPtr = b; i < arraySize;       cout << "A[" << i << "]: " << *(aPtr++) << endl,       cout << "B[" << i << "]: " << *(bPtr++) << endl, i++); } int main() {   const int arraySize = 10;   int* a = new int[arraySize];   int* b = new int[arraySize];   int* aPtr;   int* bPtr;   int i;   // initialise   for (i = 0, aPtr = a, bPtr = b; i < arraySize; *(aPtr++) = 1, *(bPtr++) = 2, i++);   // print   print(a, b, arraySize);   // copy   for (i = 0, aPtr = a, bPtr = b; i < arraySize; *(aPtr++) = *(bPtr++), i++);   // print   print(a, b, arraySize); }```
• 10-21-2005
hk_mp5kpdw
Maybe:
Code:

`transform(start of array1, end of array1, start of array 2, start of sum array, plus<int>());`
Assumes array 2 and the sum array are at least as big as array 1. Need to #include the <algorithm> and <functional> headers for that to work. Still a couple details for you to work out on your own there.

Edit: Probably not the best way... but I like it.
• 10-21-2005
maro009
thanks i will try them
• 10-21-2005
dwks
Code:

`for (i = 0, aPtr = a, bPtr = b; i < arraySize; *(aPtr++) = 1, *(bPtr++) = 2, i++);`
You shouldn't cram too much into a for loop (or while loop) header. It can get hard to read.

BTW, instead of *(aPtr++) you can use *aPtr++.
• 10-21-2005
Ancient Dragon
Quote:

Originally Posted by dwks
You shouldn't cram too much into a for loop (or while loop) header. It can get hard to read..

Amen to that! :D It also makes debugging a nightmare, and you will hate yourself for doing that in a very short time when you have forgotton what that is supposed to do. :eek: and that semicolon at the end of the line will cause many hours of grief if you ever decide to add code that should be executed on every iteration of the loop, and you don't know why it doesn't work. :rolleyes: