Teaching the tradeoffs of the foreach loop Edit: It's been quite a while since I posted this question, and in the intervening time, I have come to love the foreach loop. However, in order to avoid invalidating answers, I leave the text unchanged below:


I personally dislike the foreach loop, so I tend to avoid them when I program.  However, in spite of this preference, I still end up teaching about them as part of the AP Computer Science A curriculum.

 for (Type item : iterableCollection) {
      // Do something
 }


I am particularly interested in experiences from those who have actually taught this in a classroom (though, as always, pedagogic thoughts from others are also welcome).  What do you do to teach about the limitations, costs, and advantages of this loop structure?

I will put my own answer below alongside the others.
I think the advantages are huge, overwhelming.  

They avoid


off by one errors - the bane of the novice programmer 
needing to allocate an explicit iterator - avoiding adding names to the namespace. 


They enable  


thinking about iteration at a higher level than just counting
compact coding  


I use them whenever available. The collection knows its members. Just ask it to yield them up. It is a brilliant design. 

Programs in object-oriented languages like java should not have to all look like C programs, nor should the programmer have to always dip to the level of C to use them. C is a better assembler (for the pop-11). But few programs need that mind-set. 

My preference is to teach concepts from the top-down. Higher level thinking means (in part) "closer to the language of the problem". Then, when necessary go to a lower level - closer to the machine or closer to the level of the solution. In practice you seldom need to go down the scale very far for students to get it. And you never need to recapitulate the entire history of computing to have students understand how to work in modern languages, whatever the paradigm. 



I actually try to move even further up the abstraction scale as illustrated in this  post https://cseducators.stackexchange.com/a/1379/1293

I include this in a library so that students learning other things can do simple iterations even before loops are discussed. It is quite useful to be able to do something a fixed number of times without formally counting it. However, it is only especially useful if you want to delay for and while so that you can teach, say, object-oriented abstraction principles.