Code:
arr = [1,2,3,4,5,6,7];
function alternateAddSubtract(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
sum += arr[i];
} else {
sum -= arr[i];
}
}
return sum;
}
document.write(alternateAddSubtract(arr));
Result:
4
No comments:
Post a Comment