This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# enhanced for loop

Emily Vieille
Greenhorn
Posts: 5
how would you alternately add and then subtract individual elements of the array of the enhanced for loop from an accumulator? I'm not really sure how to seperate them... so far I have:

so for example how would you add 1 then subtract 4 add 9, etc? I'm not sure if that's right...

Kaydell Leavitt
Ranch Hand
Posts: 690
Use the modulus operator:

x % 2

If the remainder is zero, you know that you have an even number. If the remainder is one, then you know that you have an odd number.

Then you use the if and the else keywords to either add or subtract.

You don't want to add or subtract x. You want to add or subtract the elements of the array which would be:

data[x]

-- Kaydell
[ December 05, 2006: Message edited by: Kaydell Leavitt ]

Emily Vieille
Greenhorn
Posts: 5
thanks but they're not only even/odd every other one

Keith Lynn
Ranch Hand
Posts: 2409
I would respectfully disagree with some of what Kaydell said.

The variable x in the enhanced for loop is the element of the array, not the subscript.

In order to do what you want to do, you would need to use the other variable count that you have and increment it in your loop, then you could use the modulus operator on count.

I think it might be easier in accomplishing your goal to use a regular for loop.

Kaydell Leavitt
Ranch Hand
Posts: 690
I agree with Keith. x is not the loop counter, as Keith said, it is the element of the array. I'm not used to the for-each loop. I agree with Keith too that using a regular for loop is best because then you have access to the variable that counts the iterations of the loop.

-- Kaydell

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15574
46
When you use the new for loop syntax, you don't have access to the loop index. So you can't see if the index is even or odd.

You could do it simply with a boolean flag that you flip in each iteration of the loop:

or, with a more compact syntax:

[ December 06, 2006: Message edited by: Jesper Young ]

Emily Vieille
Greenhorn
Posts: 5
ok thanks everyone for the help!