Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

enhanced for loop

 
Emily Vieille
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks but they're not only even/odd every other one
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 15483
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok thanks everyone for the help!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic