Reputation: 901
int n, total, array[4] = {5,4,2,7}
for (n =0; n<4; n++)
{
total = array[n] + array[n+1];
}
5+4=9+2=11+7=18
I know that I need to store the value of the sum into a variable but how do I make the variable loop back to be added to the next number in the array.
Upvotes: 0
Views: 6750
Reputation: 16406
Your code sets
total = array[0] + array[1]
-> 9
then
total = array[1] + array[2]
-> 6
then
total = array[2] + array[3]
-> 9
then
total = array[3] + array[4]
-> undefined behavior
which of course not what you want. You ask
I know that I need to store the value of the sum into a variable but how do I make the variable loop back to be added to the next number in the array.
Well, the variable is total
, and you want to add it to the next number in the array; that's simply
total = total + array[n]
(or total += array[n]
).
All that remains is to initialize total = 0
so that the first add (total = total + array[0]
) sets total
to array[0]
rather than some undefined value.
Upvotes: 1
Reputation: 145
You don't have to do the array+1 position adding. Only have to accum the values in one variable
// Declaration of total variable and values array
int total=0, array[4]={5,4,2,7}
// For loop
for (int n=0; n<4; n++) {
// Total accum
total+=array[n];
// Use += or you can use too this: total=total+array[n];
}
Upvotes: 3
Reputation: 1182
int n, total = 0, array[4] = {5,4,2,7}
for (n =0; n<4; n++)
{
total += array[n];
}
Upvotes: 5