This week's book giveaway is in the Jobs Discussion forum. We're giving away four copies of Soft Skills and have John Sonmez on-line! See this thread for details.

Enhanced for loops work pretty much as you would expect, following the logic "for each whatever in a list of whatevers do something".

However, this:

is changing your list of "whatevers" while you iterate through it, so that will muddy the waters a bit.

Think about it:

The first iteration, i == 1, so you change the second element in your arr to be 0.

The second iteration, i == 0 (because you changed this value in the first iteration) so you change the first element of arr to be 0.

The third iteration, i == 3, so you change the forth element in arr to be 0.

The forth iteration, i == 0 (because you changed this value in the third iteration) so you change the first element of arr to be 0.

And so on. Stick in some debug lines to watch what the values are doing if you don't quite follow the above. [ April 09, 2008: Message edited by: Paul Sturrock ]

First time thru the first loop i will be 1, so it sets the second element of your array (arrays are zero based) to 0, so your array contains {1,0,3,4,5,6,7,8}

Second time thru the first loop i will be 0, so it sets the first element of your array to 0, so your array contains {0,0,3,4,5,6,7,8}

Third time thru the first loop i will be 3, so it sets the fourth element of your array to 0, so your array contains {0,0,3,0,5,6,7,8}

Fourth time thru the first loop i will be 0, so it sets the first element of your array to 0, so your array contains {0,0,3,0,5,6,7,8}

Fifth time thru the first loop i will be 5, so it sets the sixth element of your array to 0, so your array contains {0,0,3,0,5,0,7,8}

Sixth time thru the first loop i will be 0, so it sets the first element of your array to 0, so your array contains {0,0,3,0,5,0,7,8}

Seventh time thru the first loop i will be 7, so it sets the eighth element of your array to 0, so your array contains {0,0,3,0,5,0,7,0}

Eigth time thru the first loop i will be 0, so it sets the first element of your array to 0, so your array contains {0,0,3,0,5,0,7,0}

Everything Paul says is precisely correct, but he may have left out an explicit statement of the misunderstanding: the variable "i" takes the values in the array, one at a time, not an array index!

I appriciate JavaRanch for its wonderful services and I thank Paul Sturrock, Balasubramani Dharmalingam , Joanne Neal and Ernest Friedman-Hill for explaining the "for each" behavior. I have understood the concepts.