# Alternating Sum

• 02-10-2009, 11:19 PM
ScaryJello
Alternating Sum
I am attempting to write a method that is passed an array and its size. The array is filled by the user with integers. What i need it to do is alternate addition and subtraction using a for loop.

Example:

User enters: 1 4 9 6 7 18 9 ...

I need the math to look like this:
1 - 4 + 9 - 6 + 7 - 18 + 9.

Thank You
• 02-11-2009, 12:08 AM
angryboy
array begin w/ 0,1,2,3,4... so you can write a loop to negate the odd index.
e.g.:
1 -4 9 -6 7 -18 9
then add them in another loop.
ans = -2
• 02-11-2009, 12:22 AM
ScaryJello
I can't do that though. This assignment is for a class and we have not learned how to negate the odd index yet. I was thinking more along the lines as to multiplying by -1 to negate the number. I cant call an array literal either

public static int alternatingSum(int[] nums, int numsSize)
{
int total = 0;
for(int i = 0; i < numsSize; i++)
{
total += nums[i];
}
}

Obvi this adds the numbers together. Now i just need to make it so it alternates. Hope someone can help...
• 02-11-2009, 12:32 AM
CJSLMAN
• You really don't need to pass the size of the array as an argument (unless it's a requirement). You can figure out the size of the array within the method.
• You really don't need to use an array for this activity (again... unless it's a requirement).
Question:
• Are even numbers subtracted or are odd indexed numbers subtracted?

Luck,
CJSL

Edit: forget the question... you some how have figured out how to get the numbers in the array... that's why I was asking
Edit 2: decided to change the question
• 10-13-2009, 08:36 AM
TimboTheChamp
Couldn't you write a loop that only counts every second index.

ie.
public int alternatingSum()
{
sum = 0;
for(i = 0; i < num; i = i + 2) {
sum = sum + anArray[i] - anArray[i + 1];
}
return sum;
}
• 10-13-2009, 09:09 AM
Vio
so you haven't learnt the meaning of %? Otherwise you could use an if-statement
if (i % 2 == 0) // check if it's even
do ...
else
do ...
or TimboTheChamp his solution looks fine too.
but make sure you don't get an indexOutOfBoundsException.
• 10-13-2009, 09:18 AM
TimboTheChamp
yeh just realised that when I tried to run it. The condition has to be changed to:
i < (num-1)