What to use

Nov 8, 2012 at 7:22am
Hello
i just want to know what can i use to add the elements of two given arrays

i have tried for and failed big time so did i make a problem or is it not for to begin with?

thank you in advance
Nov 8, 2012 at 10:30am
Add them in what way? Into one single sum, or the elements added individually into a new array, or each array added separately to give you the sum of each array?
Nov 8, 2012 at 12:03pm
For example you can use a loop or some standard algorithm.:)
Nov 8, 2012 at 3:36pm
+
Nov 8, 2012 at 7:35pm
No i need to add them in a single sum
but it only adds the first number of the first array with the first number of the second array and so on
Nov 8, 2012 at 7:54pm
If your arrays have equal numbers of elements then you can use standard algorithm std::inner product. Otherwise you can use standard algorithm std::accumulate. For example

1
2
3
4
5
6
7
8
9
10
11
12
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int b[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

int sum = std::inner_product( std::begin( a ), std::end( a ), std::begin( b ), 0,
		                          std::plus<int>(), std::plus<int>() );

std::cout << "sum = " << sum << std::endl;

sum = std::accumulate( std::begin( a ), std::end( a ),
			std::accumulate( std::begin( b ), std::end( b ), 0 ) );

std::cout << "sum = " << sum << std::endl;
Last edited on Nov 8, 2012 at 7:55pm
Nov 8, 2012 at 8:00pm
WOW
i am still a beginner , i have no idea what is this std::
can you explain it if thats not too much to ask ?
Nov 8, 2012 at 8:11pm
In fact I wrote

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int b[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

int sum = 0;

for ( int i = 0; i < sizeof( a ) / sizeof( *a ); i++ ) sum += a[i] + b[i];

std::cout << "sum = " << sum << std::endl;

sum = 0;

for ( int i = 0; i < sizeof( a ) / sizeof( *a ); i++ ) sum += a[i];
for ( int i = 0; i < sizeof( b ) / sizeof( *b ); i++ ) sum += b[i];

std::cout << "sum = " << sum << std::endl;


If you do not like std:: then you can write at the very beginning

using namespace std;

and then remove all occurences of std::

:)
Last edited on Nov 8, 2012 at 8:14pm
Nov 8, 2012 at 11:29pm
A namespace is simply a reference to a particular context, some things require this context (like cout). For more detailed info go to:

http://www.cplusplus.com/doc/tutorial/namespaces/

As far as your arrays go, you could do something like this:

1
2
3
4
5
6
7
8
9
10
int i, sum1=0, sum2=0, total;
int maxindexa, maxindexb; //These are the last array index number for your arrays
//here you would assign maxindexa and maxindexb
for(i=0;i<=maxindexa;i++) {
   sum1+=a[i];
}
for(i=0;i<=maxindexb;i++) {
   sum2+=b[i];
}
total = sum1 + sum2;


Very simple
Last edited on Nov 9, 2012 at 2:18am
Topic archived. No new replies allowed.