Results 1 to 7 of 7
Thread: Alternating Sum
- 02-10-2009, 10:19 PM #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.
Can someone please help me?
Thank You
- 02-10-2009, 11:08 PM #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 = -2USE CODE TAGS--> [CODE]...[/CODE]
Get NotePad++ (free)
- 02-10-2009, 11:22 PM #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];
}
return total;
}
Obvi this adds the numbers together. Now i just need to make it so it alternates. Hope someone can help...
- 02-10-2009, 11:32 PM #4
Some comments...
Comments:
- 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).
- 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 questionLast edited by CJSLMAN; 02-10-2009 at 11:37 PM.
Chris S.
Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.
- 10-13-2009, 08:36 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;
}
- 10-13-2009, 09:09 AM #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.
- 10-13-2009, 09:18 AM #7
Member
- Join Date
- Oct 2009
- Posts
- 2
- Rep Power
- 0


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks