0
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.

3 Answers 3

5
int n, total = 0, array[4] = {5,4,2,7}

for (n =0; n<4; n++)
{
  total += array[n];
}
Sign up to request clarification or add additional context in comments.

2 Comments

ah forgot about the compound assignment
@thao nguyen: the compund assignment is nothing special here, you could also write it total = total + array[n]. The total on the left is the value of the variable before the assignment.
3

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];
}

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.