1. Member
Join Date
Feb 2009
Posts
8
Rep Power
0

## 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

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

3. Member
Join Date
Feb 2009
Posts
8
Rep Power
0
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...

• 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
Last edited by CJSLMAN; 02-11-2009 at 12:37 AM.

5. Member
Join Date
Oct 2009
Posts
2
Rep Power
0
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;
}

6. Member
Join Date
Oct 2009
Location
Belgium
Posts
18
Rep Power
0
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.

7. Member
Join Date
Oct 2009
Posts
2
Rep Power
0
yeh just realised that when I tried to run it. The condition has to be changed to:
i < (num-1)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•