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?
Printable View
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?
What have you tried?
For Loop Example:
Code:for(int i = 0; i < ARRAY_SIZE; i++){
}
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?
Well, suppose you have two variables, sum and x. To add x to sum, you would write:
Code:sum += x;
So for multiple variables, say x, y, z, it would be like this?: x+=y+=z;
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.
Oh ok. So it would be: sum += x ; Where x is just the name of the array?
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.
Elkvis- I appreciate it but Googling it is what led me this forum in the first place
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,
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.Code:for(int i=0; i < array_size; i++)
sum=sum + myarray[i]; //or sum += myarray[i]
cout << sum;