Hey, i was having trouble figuring out how to add array numbers besides:
array[0]+array[1]+array[2]........
I'm trying to figure out how to do the addition with a for statement or something.
Any Help!?!?!?!?
thanks
Printable View
Hey, i was having trouble figuring out how to add array numbers besides:
array[0]+array[1]+array[2]........
I'm trying to figure out how to do the addition with a for statement or something.
Any Help!?!?!?!?
thanks
Code:--
--
sum=0;
for(i=0;i<10;i++)
sum=sum+arr[i];
cout<<"ARRAY TOTAL : "<<sum;
--
--
Try this:
the += in that means, "this variable equals itself plus this"Code:
int array [] = {3, 6, 9, 12, 15}; //your array...
int n, result=0;
for ( n=0 ; n<5 ; n++ )
{
result += array[n];
}
cout << result;
This works, I hope the explanation is good enough.
Code:#include <iostream.h>
int main(void)
{
int count, sum=0; //count is the for loop control variable
int array[5];
/*start count at 0 as that is the first element in the array, count goes up
to 4, as 0 to 4 equals the 5 elements in the array, the count ++ means add 1 to
the count each time the loop goes round, you use count in the brackets of array
to tell it which element to first initialise to its own number (0,1, 2, 3, 4)
and then to add that to the sum variable*/
for (count=0; count<=4; count++)
{
array[count]=count;
sum=sum+array[count];
}
cout<<"array sum: "<<sum; //print out sum because you have added the elements to it
return 0;
}
thanks, that was a no brainer.