-
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
-
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
-
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...
-
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).
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
-
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;
}
-
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.
-
yeh just realised that when I tried to run it. The condition has to be changed to:
i < (num-1)