Array question (+=)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// arrays example
#include <iostream>
using namespace std;

int array [] = {2, 4, 6, 8, 10};
int n, result=0;

int main ()
{
  for ( n=0 ; n<5 ; n++ )
  {
    result += array[n];
  }
  cout << result;
  return 0;
}


This output is 30. Which add ups all of the indexes in the array.

What does result += array[n]; do? It adds up the index values from 1-5 and adds them to result, right?

Why does when I take out the + so it is result = array[n]; it equals 10?
1) What '+=' does is equal the left hand value (of the operand) to the 'left hand value + the right hand value'.

Therefore you get:

result = 0;

result += 2; so result equals 2
result += 4; so result already has a value of 2, now 4 is added to it
result += 6; so result already has a value of 6, now 6 is added to it
etc...

2) If you tak away the '+' sigin you are just equaling 'result' to that element of the array. As 10 is the lsat element, that is your final answer.
result += array[n] is the same as result = result + array[n] array[n] returns the (n-1)th element of the array so (as the value of n changes in the loop) it will result the sum of all array elements.
if you remove the +, it will assign result to the (n-1)th element of the array discarding the previous value. So at the end of the loop result would be equal to array[4]
Thanks. This makes sense now.
Topic archived. No new replies allowed.