# Thread: Adding an array using a For loop

1. ## Adding an array using a For loop

I need to add the elements of an array together using a for loop and then print the result. I know it is a simple code but I am struggling with it. Can anyone offer any advice on this?

2. What have you tried?

3. For Loop Example:
Code:
```for(int i = 0; i < ARRAY_SIZE; i++){
}```

4. I'm kinda stuck at the starting point (I'm just learning this stuff). I know the basic code structure but I am struggling with the body of it. The basic structure of the for loop does help. For instance, say you had to add together 1,2,3 and 4 using a for loop. What would that look like?

5. Well, suppose you have two variables, sum and x. To add x to sum, you would write:
Code:
`sum += x;`

6. So for multiple variables, say x, y, z, it would be like this?: x+=y+=z;

7. Nope, unless you intend to add z to y as well. In this case you are summing the elements of an array, one at a time.

8. Oh ok. So it would be: sum += x ; Where x is just the name of the array?

9. No, where x is the current element of the array, i.e., you would replace x with say, y[i], where y is the array name and i is the array index.

10. Elkvis- I appreciate it but Googling it is what led me this forum in the first place

11. You could need to declare a variable to hold the sum , ie. int sum=0;

Then use a for loop to go through the elements of the array, and add it to sum.

As such,

Code:
```for(int i=0; i < array_size; i++)
sum=sum + myarray[i]; //or sum += myarray[i]

cout << sum;```
All this is doing is accessing the element of the array, and adding it to the value in sum, so you get the total of the array.

Popular pages Recent additions