English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Write a function

double alternating_sum(vector a)
that computes the alternating sum of all elements in a vector. For eg, if 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

2007-01-05 19:04:30 · 2 answers · asked by Anonymous in Computers & Internet Software

2 answers

check http://www.pscode.com for great examples. You forgot to mention which language you wanted the function in.

2007-01-05 19:13:17 · answer #1 · answered by Richard H 7 · 0 0

This one is close to the other function you needed. Come on - can't you figure this out yourself?

Loop through the array and each time through, determine if this is an even iteration or an odd iteration. (Hint - use the modulo operator.) If odd, subtract the array item from your running summ. If even, add it.

Now go write the code!

2007-01-06 03:36:37 · answer #2 · answered by BigRez 6 · 0 0

fedest.com, questions and answers