Write a function that computes the alternating sum of all elements in a
alternating_sum is called with a vector containing
1 4 9 16 9 7 4 9 11
Then it computes
1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = -2
Can anyone write this code for c++?
Take a look at here:
http://www.msoe.edu/eecs/cese/resources/...
Subscribe to:
Post Comments (Atom)
Use a for loop and mod (%) with the iterator.
ReplyDeleteint altSum = 0;
for (int i = 0; i < alternating_sum.length(); ++i)
{
if (i % 2 == 0)
{
altSum += alternating_sum[i];
}
else
{
altSum -= alternating_sum[i];
}
}