<p><a href="https://ruby-lang.org" rel="nofollow noreferrer">Ruby</a> would be a really interesting language for you to work with, given your dislike of foreach loop.  It provides an good way to think about a for loop. In ruby, the <code>for</code> keyword does not exist. There's no way to actually create a for loop. But any collection (<code>Enumerable</code>) has a <code>#each</code> method, which iterates of the elements of the collection. For example:</p>

<pre><code>words = ["apple", "car", "coffee", "document"]
words.each do |word|
  puts word
end
#=&gt; apple
#=&gt; car
#=&gt; coffee
#=&gt; document
</code></pre>

<p>To implement a traditional <code>for</code> loop, you need to iterate over a range (in ruby the <code>a..b</code> notation generates an Enumerable from a to b):</p>

<pre><code>words = ["apple", "car", "coffee", "document"]
[0..3].each do |i|
  puts words[i]
end
#=&gt; apple
#=&gt; car
#=&gt; coffee
#=&gt; document
</code></pre>

<p>Which syntax makes more conceptual sense and is more readable? I'd certainly say the first one. It also will help students seperate the concept of a loop with the specific syntax for creating a loop.</p>

CC BY-SA 3.0
2018-02-04T15:01:37.320Z
2018-02-04T15:01:37.320Z
thesecretmaster
<p>There is no "limitation" or "tradeoff".</p>

<p>The point is, we express ideas at a given level of abstraction.</p>

<p>The "forall" is for ranging over the values in a collection.</p>

<p>The for(int i = 0; i &lt; n; i++) etc is for ranging over numbers, that sometimes happen to be the valid indices in some array. Quite a different matter.</p>

<p>Use the appropriate level of abstraction. The for loop is not a limitation over the while loop, or goto+if constructs.</p>

<p>Edit: actually some colleagues don't want to teach the foreach, because it comes with a break when you want to leave it before its natural end, which happens rather frequently.</p>

<p>And, you know, break is somehow like goto, which is considered awful and definitely forbidden. Burn these heretics and their for each loop!</p>

CC BY-SA 4.0
2020-01-26T18:29:22.123Z
2020-01-27T06:21:00.863Z
2020-01-27T06:21:00.863Z
Michel Billaud
<p>Don't forget to mention what information is not available when they choose between certain looping constructs:</p>

<p>foreach loops lose position data (index, relative locations (i and i-1, etc)
for(int i;;) loops lose the index variable (i) upon completion of the for loop</p>

<p>foreach loops are designed to work with collections &amp; iterators.</p>

<p>See <a href="https://cseducators.stackexchange.com/questions/2632/teaching-the-humble-for-loop/4301#4301">Teaching the humble for loop</a></p>

<p>Also from a AP CS A exam perspective, the trap is usually that you don't have an index value. The advice I give to the students taking this exam is to avoid the foreach when writing exams because in the majority of cases they will require the index.</p>

CC BY-SA 3.0
2018-02-07T14:11:24.547Z
I encourage you to fill out your answer. Short answers like this tend to get ignored, or worse. Help future readers draw the correct inferences that you see yourself.
Buffy
CC BY-SA 3.0
2018-02-07T15:07:30.640Z
Your students would need to be aware of the the issues around using iterators -- attempts to modify the underlying collection, copied elements, etc.
Mr Bradley
CC BY-SA 3.0
2018-02-07T14:06:42.927Z
2018-02-07T15:02:51.217Z
2018-02-07T15:02:51.217Z
Mr Bradley
<p>I like this loop. A lot.  You don't go out of bounds.  It eliminates an important source of errors. I encourage its use when iterating through collections. I also ask students who make collections to implement Iterable so that they can use the collections <code>for</code> loop on their custom collection.</p>

CC BY-SA 3.0
2017-07-18T01:47:16.670Z
2017-07-18T01:47:16.670Z
ncmathsadist
<p>I think foreach loops are great, and are almost always preferred over for loops. While for loops are fundamental material and definitely should be covered, they're sort of infrequently used in practice -- when iterating, we almost always iterate over lists and other collective (and it's generally considered bad practice to modify a data structure you're iterating over anyways, so it's no big deal if we lose that -- see the recent trend towards functional programming and immutable data structures).</p>

<p>(After all, there's a reason why languages like Python basically got rid of for loops in favor of foreach loops! Generally, when you're looping, it's because you're looping over lists, sets, collections, or infinite generators.)</p>

<p>That said, it would probably be a bad idea to introduce foreach loops immediately. In the courses I help teach, we wait until we've introduced the following concepts first:</p>

<ol>
<li>Using regular for loops</li>
<li>OOP</li>
<li>Using basic data structures (ArrayList, LinkedList, Stack, Queue, etc)</li>
</ol>

<p>Once we hit that point, we typically do the following:</p>

<ol>
<li>Start by talking about sets and maps (in a previous lesson).</li>
<li>Intentionally run into a limitation: if hash sets are inherently unordered, and the concept of getting the "i-th" element of a hashset is simply undefined, how do we iterate over it? This serves as a great motivator for why we need a new looping concept (if you introduce foreach loops earlier, students are likely to brush this off by treating as only a mildly more convenient form of a for loop, which is missing the point).</li>
<li><p>Rather then jumping into foreach loops, we detour by talking about iterators. Time permitting, we implement a basic one for an arraylist we previously wrote together in class -- the goal is to demystify each step.</p>

<p>We have students use Scanners to do file IO/string parsing in previous assignments, so they usually get the hang of using iterators pretty quickly/find they have a good intuition for using iterators.</p>

<p>If we're feeling really ambitious, we can discuss this lets us implement data structures that are infinitely long.</p></li>
<li><p>But of course, iterators are pretty clunky, so that serves as good motivation for the final part of the lesson: foreach loops. We introduce the notion of "syntactic sugar", and demonstrate how Java internally rewrites the foreach loop into a while loop using an iterator. (This helps demystify a lot of the "magic" of foreach loops for students). </p></li>
<li><p>We finish by talking about some of the limitations of foreach loops (e.g. you can't modify the collection you're iterating over) and discuss stylistically when you should use for loops vs iterators vs foreach loops.</p>

<p>If you have time, this would also perhaps be a good place to discuss how it can be useful to intentionally <em>limit</em> what you can do in order to gain something in exchange. In this case, we exchange the ability to modify our data structure in exchange for cleaner and more readable code and the ability to iterate over a wider variety of data structures. This actually echos some of our earlier discussions on hashmaps/hashsets -- by removing "indexability", we were able to get faster lookups.</p></li>
</ol>

<p>All of this usually takes about one hour-long lesson, assuming you've covered basic usage of maps and sets in a previous lesson.</p>

<p>Finally, to help reinforce the point, we start mandating that students use foreach loops whenever possible on their homework, and start deducting points if they use for loops in places where it's not the best option.</p>

<p>The very next homework assignment requires students to manipulate and iterate over sets and maps, so in practice it's almost impossible for students to lose points for this.</p>

CC BY-SA 3.0
2017-07-14T23:41:52.227Z
2017-07-15T00:05:51.463Z
2017-07-15T00:05:51.463Z
Michael0x2a
<p>There is much discussion here about how a traditional <code>for</code> seems more powerful than a <code>foreach</code>, but a traditional <code>for</code> with sentinel value can only be used to iterate over an indexable collection. Data structure like sets and maps are prevalent, and iterating over them by index would be technically and conceptually absurd. (You've already outlined places where <code>for</code> is invaluable, but it's applicability is technically limited to only a few (granted, extremely common) types).</p>

<p>Furthermore, good code expresses intent, which is why we have types like 'bag' which may seem just like an inferior list/vector: if you have data which is conceptually unordered, then you are imposing a layer of complexity on the mapping between code and reality by using a outwardly ordered data structure (e.g. <code>ArrayList</code>)...</p>

<p>... <code>foreach</code> is about enumerating/iterating over collections, and expresses the intent <em>much</em> more clearly and succinctly than a traditional <code>for</code> loop, which is just a familiar and tidy way of expressing an equivalent while loop. <code>foreach</code> lets you exploit the <code>ICollection</code>, or <code>Iterable</code>, or <code>IEnumeable</code> abstraction, which is fundamental to reusable collection handling code (I'm a C#er, not sure what the Java interfaces are called).</p>

<p>Others have already detailed why <code>foreach</code> is great for maintainability (aside from expressing the intent of the code better, it's <em>so much harder</em> to get wrong, and even <em>easy</em> to get right), and I would agree/suggest that you should typically use a <code>foreach</code> whenever you can quickly work out how to do so. For example, if you need to keep track of the previous value in the loop (see Buffy's answer), this is readable and easy enough to write in a <code>foreach</code> loop that the benefits of having a more general purpose piece of code (<code>foreach</code> will work on any collection) will be of sufficient value to eclipse any perceived greater clarity in the for loop.</p>

<p>I'll just add that even if you are throwing together code you don't expect other people to see, or to even look at yourself in the future, writing at a high level of abstraction helps to prevent errors, and gives your type system the best chance of catching mistakes for you. If you are just iterating over the values in a collection (which happens <em>a lot</em>) then use a <code>foreach</code> loop <em>because</em> it is less powerful: you've told the code that you don't want to modify the collection, now when you try to, your language can scream and shout at you (that's its job!).</p>

<p><em>Just for reference, I'm a C#er who has done a lot of (C#) code-golf. I love traditional <code>for</code>-loops, and can surely read and write them quicker than most: both loops are applicable in many places in the real world; <code>foreach</code> usually wins out where they overlap.</em></p>

CC BY-SA 3.0
2017-07-15T10:55:25.220Z
Agreed, I just posted a comment myself about the ability of iterators to represent unindexable data and agree it's a really important point - iterators are a simpler interface that requires less of your data source, meaning they generally scale better. Likewise, the things iterators can't do are mostly language limits of Java (no tuples, no returning references to items in a list) rather than strict limitations of the concept themselves.
Gareth Latty
CC BY-SA 3.0
2017-07-15T11:08:05.237Z
I note that I am _especially_ careful when I write code only for myself. Indentation, brace all, intention revealing names, ... All of it. I know that if it is just for me, I'll return to it later and don't want to have to de-obfuscate my own code. And I especially don't want to have to add braces to code that omitted it on an update. Get it right. Get it done.
Buffy
CC BY-SA 3.0
2017-07-15T10:52:11.813Z
2017-07-15T11:20:44.057Z
2017-07-15T11:20:44.057Z
VisualMelon
<p>I think the advantages are huge, overwhelming.  </p>

<p>They avoid</p>

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

<p>They enable  </p>

<ul>
<li>thinking about iteration at a higher level than just counting</li>
<li>compact coding  </li>
</ul>

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

<p>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. </p>

<p>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. </p>

<hr>

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

<p>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 <code>for</code> and <code>while</code> so that you can teach, say, object-oriented abstraction principles.</p>

CC BY-SA 3.0
2017-07-15T03:57:26.930Z
Speaking as a Java programmer, not a teacher, I only use the old style loops when there is a clear benefit. The foreach loop can compile more efficiently, and as Buffy says they prevent common errors that beginners are prone to make, but also plague more experienced programmers who get a little lax.
pojo-guy
CC BY-SA 3.0
2017-07-14T22:04:57.010Z
2018-02-04T02:21:14.323Z
2018-02-04T02:21:14.323Z
Buffy
<p>To do something like the following with foreach...</p>

<pre><code>// Exercise 3:
for (int j = 1; j &lt; myDoubles.size(); j++){
   if (myDoubles.get(j) &lt; myDoubles.get(j-1))
        return false;
return true;
</code></pre>

<p>consider the following, expressed as a static method</p>

<pre><code>public static boolean isSorted(ArrayList&lt;Integer&gt; values){
    boolean first = true;
    Integer previous = Integer.MIN_VALUE;
    for(Integer value: values){
        if(first){
            first = false;
        } else {
            if (value &lt; previous){
                return false;
            } 
        }
        previous = value;               
    }
    return true;
}
</code></pre>

<p>I won't try to argue that this is simpler, however it does illustrate some important techniques useful elsewhere. The processing of the first element is handled explicitly, often important to do. In the original <code>for loop</code> version it is handled by starting at 1, which is easy to miss. The other technique is the handing off of a current value to a previous reference. There are a couple of other simpler things here, such as MIN_VALUE (which isn't used, but avoids an uninitialized value - that will fail the &lt; test also). A slight modification would work for Doubles, of course. </p>

CC BY-SA 3.0
2017-07-14T23:26:26.773Z
I stand by the pedagogic usefulness of my example, though I will add yours into my future discussions of the  tradeoffs. If you add an extra int, then there are no limits on power, because you could also just add back in the missing sentinel value. But the complexity of the code rises, and the fact that you're not given a sentinel in the first place is still a limit of the form itself that you must work around. And without the additional variable, the sequential comparison is not possible.
Ben I.
CC BY-SA 3.0
2017-07-14T23:59:42.000Z
@BenI: a third alternative you could bring up is implementing a helper function that transforms an iterable into an iterable of pairs and foreach over that. The syntax is still a bit clunky because Java had no built-in syntax for manipulating/destructuring types, but it would make the foreach approach clean again/visually similar to the for loop solution. It's perhaps cheating in the context of your exercise since we're not sticking with just foreach loops, but this would be a good opportunity to help students start thinking about iteration on a higher level.
Michael0x2a
CC BY-SA 3.0
2017-07-15T17:10:46.800Z
See my comment on @BenI.'s answer: Using `java.util.Optional` makes this *much* simpler, because you don't need to have a special case to handle the first iteration (the different behaviour of `Optional.empty()` vs `Optional.as(value)` handles it for you). And this is, perhaps, an important point here: working in the `foreach` style requires a slightly different approach, and the tools to make that approach convenient have taken a while to get here (at least in Java... Optional types have been around for years in functional languages), but now they are it is critical to learn how to use them.
Jules
CC BY-SA 4.0
2017-07-14T23:16:54.683Z
2020-01-23T15:40:33.157Z
2020-01-23T15:40:33.157Z
Buffy
<p><strong>Part 1</strong></p>

<p>When I introduce the <code>foreach</code> loop, I do it the context of a lecture on ArrayLists and wrapper classes.  I first just kinda slip it in unannounced:</p>

<pre><code>double total = 0.0;
for (double currentValue : myDoubles)
    total += currentValue;
System.out.println(total);
</code></pre>

<p>Then we turn to it and begin to break it apart a little.  I first compare it to</p>

<pre><code>for (int j = 0; j &lt; myDoubles.size(); j++){
    double currentValue = myDoubles.get(j);
</code></pre>

<p>.  But then I tell the students that there is a hidden limitation.  I want to see if they can spot it, and I provide them with three re-writing exercises (that are also practice exercises on the prior concepts) to help them find it:</p>

<pre><code>// Exercise 1:
double total = 0.0;
for (int j = 0; j &lt; myDoubles.size(); j++){
    total += myDoubles.get(j);

// Exercise 2:
for (double currentValue : myDoubles)
   total += currentValue;

// Exercise 3:
for (int j = 1; j &lt; myDoubles.size(); j++){
   if (myDoubles.get(j) &lt; myDoubles(get(j-1))
        return false;
return true;
</code></pre>

<p>When the last one turns out to be impossible, we discuss the limits imposed by not having a sentinel value.</p>

<p><strong>Part 2</strong></p>

<p>We revisit <code>foreach</code> loops later in the year when we deal with multi-dimensional arrays.  Towards the end of that lesson, they are given this task:</p>

<blockquote>
  <p>For some int[][] ma, fill every element with the value 3.</p>
</blockquote>

<p>We discuss the standard <code>for</code> loop solution:</p>

<pre><code>for (int y = 0; y &lt; ma.length; y++)
    for (int x = 0; x &lt; ma[y].length; x++)
        ma[y][x] = 3;
</code></pre>

<p>And then I bring them back to <code>foreach</code> with this pretty-looking thing:</p>

<pre><code>for(int[] outer : ma)
    for(int x : outer)
        x = 3;
</code></pre>

<p>... which, of course, doesn't work at all. I ask the kids to pair up and try to figure out <em>why</em> before we all come back together to have a discussion.</p>

<p>This example brings us right to the heart of copy-by-value (and provides another chance for us to revisit references).  I consider the discussion over only when the students seem to understand why the nested <code>foreach</code> doesn't work, but this loop does:</p>

<pre><code>for(int[] outer : ma)
    for(int x=0, x&lt;outer.length; x++)
        outer[x] = 3;
</code></pre>

CC BY-SA 3.0
2017-07-15T10:45:51.703Z
I think if you are going to talk about the limits, an interesting point to make is that Java's limited support for things like tuples make it harder to implement good solutions inside iterators. Python, for example, makes part 1 rather easy (`any(first < second) for (first, second) in zip(items[1:], items))`). Likewise, `C#`'s `ref` returns could be used to solve the second case (although they aren't, as far as I know). I think it's valuable to note that the iterator provides a lot of value but in some cases is too limited (by it's design in that language) to solve some problems.
Gareth Latty
CC BY-SA 3.0
2017-07-15T10:50:49.810Z
Most importantly, it's increasingly common for programmers to have to deal with large amounts of data, and storing all of your data in memory isn't always possible. Traditional indexing `for` loops are generally useless when dealing with lazy data, and so understanding how to do things with iterators rather than indexing means your code can scale far more effectively.
Gareth Latty
CC BY-SA 3.0
2017-07-15T16:55:31.043Z
"When the last one turns out to be impossible"... `Optional<Double> last = Optional.empty(); for (Double d2 : myDoubles) { if (last.map(d1 -> d2 < d1).orElse(false)) return false; last = Optional.of(d2); }`. Ok, it's a *little* harder to understand at first grasp than yours, but has the advantage that it's O(n) for all standard collection classes, whereas your version is O(n^2) for linked lists, and is also thread safe if `myDoubles` is a concurrent collection. And it promotes a way of thinking about the problem that is more generally useful and less fragile than working directly with indices.
Jules
CC BY-SA 3.0
2017-07-15T17:35:44.570Z
(and yes, I do think these concepts are fundamental enough that they should be taught early enough that students looking at the `foreach` loop should already know about them: the "optional" container type, lambda functions, "map" functions on containers -- we think of them as advanced topics because they were introduced late to most of our popular languages, but the different way of thinking about problems they enable can make for much better code in many situations, and they should therefore probably be our first choice for tackling most problems, so why not teach them first?)
Jules
CC BY-SA 3.0
2017-07-17T15:33:17.857Z
Oh. When I saw you talking about the limitations in the question the first one which came to mind is that you can't call `remove()` on the `Iterator`, but that doesn't seem to enter into your considerations at all. I see `for (Foo foo : foos) {` as sugar for `for (Iterator<Foo> it = foos.iterator(); it.hasNext(); ) { Foo foo = it.next();`, but all of the answers seem to be about iterating over arrays rather than collections.
Peter Taylor
CC BY-SA 3.0
2017-07-14T22:06:42.987Z
2017-07-14T22:06:42.987Z
Ben I.
<p>I don't think you should teach the <code>foreach</code> loop and then point out all of its "flaws" when compared to a traditional <code>for</code> loop. You should treat them both as tools, and different tools are used for different tasks. Maybe teach them a bit of the history (traditional <code>for</code> came first, then <code>foreach</code> was added in Java 5) and show them an example of when it would be best to use each.</p>

<p>Also note that you seem to be skipping over a third looping mechanism, which the <code>foreach</code> loop is based on: the <code>Iterator</code>.</p>

<p>Compare two tasks, like printing out every value in an <code>ArrayList</code> and removing all elements that match a certain criteria (for example, values that are less than 0). Show them how you'd do (or how it's not possible to do) each task in all <strong>three</strong> types of loop.</p>

<p>With the simple printing task, the <code>foreach</code> loop is perfect. Using a traditional <code>for</code> loop or an <code>Iterator</code> is probably overkill for this task. But with the task of removing elements, the <code>foreach</code> loop will throw an exception! If you're using a traditional <code>for</code> loop, you have to loop backwards or be very careful about which index you're looking at (otherwise you might skip elements). And an <code>Iterator</code> is probably best suited for this task.</p>

<p>The point is that everything in programming should be treated as a tool. A tool isn't inherently better or worse than other tools, it's just better suited for specific tasks. Talk about those tasks.</p>

CC BY-SA 3.0
2017-07-19T16:59:17.913Z
2017-07-19T16:59:17.913Z
Kevin Workman
<p>Addressing the subquestion regarding limitations of <code>foreach</code>: </p>

<p>I've been a reader for the AP Computer Science A exam since 2004.  The most common mistake we see in student solutions regarding <code>foreach</code> loops deals with two important limitations:</p>

<ul>
<li><p><code>foreach</code> loops lose any association between items in an ordered collection (e.g. array, <code>ArrayList</code>) and their indexes.   If the core algorithm requires knowing the location of an item as well as its value (e.g. returning the index of an item in an <code>ArrayList</code>), <code>foreach</code> loops are usually inappropriate.</p></li>
<li><p><code>foreach</code> loops cannot modify the base collection while iterating over it.   If the core algorithm requires changing the base collection, the <code>foreach</code> loop is inappropriate.</p></li>
</ul>

CC BY-SA 3.0
2017-07-23T03:13:15.363Z
Thank you for sharing your insight as an AP CS exam reader. I'll look for more of your answers.
Ellen Spertus
CC BY-SA 3.0
2017-07-23T04:14:10.457Z
Good points!  I'd also be extremely interested in your insights on [this](https://cseducators.stackexchange.com/questions/143/designing-rubrics-for-ap-computer-science-style-free-response-questions) question as well.
Ben I.
CC BY-SA 3.0
2017-07-23T02:24:42.500Z
2017-07-23T02:24:42.500Z
Jim Huggins
<p>You should definitely teach foreach loops. Why?</p>

<ol>
<li>Foreach loops are the main type of loop in Python.</li>
<li>Python is the awesomest.</li>
<li>Therefore foreach loops are important.</li>
</ol>

<hr>

<p>All "joking" aside, foreach loops are <em>super</em> useful - I use them all the time. They're the difference between</p>

<pre><code>x = 0
while x &lt; len(list):
    print(list[x])
    x+=1
</code></pre>

<p>and</p>

<pre><code>for i in list:
    print(i)
</code></pre>

<p>This illustrates a couple nice things about foreach loops:</p>

<ol>
<li>Very short, clean code.</li>
<li>Less variables to keep track of - nice for any programmer, let alone novices.</li>
<li>Much easier to iterate through lists/arrays/dictionaries/strings or perform batch operations.</li>
<li>Allows you to introduce list comprehensions much more easily (what's a list comprehension but a condensed foreach loop?), and everyone knows list comprehensions are the best thing since sliced lists.</li>
<li>Very commonly used in awesome programming languages like Python. (Seriously, though, Python's pretty commonly used - best to be prepared for using it.)</li>
</ol>

CC BY-SA 3.0
2017-07-15T17:08:54.960Z
It should be noted that Python isn't the only language where the use of iterated loops is much more common than any other type, which is perhaps an important point: you can learn to work with indices rather than iterators in some environments, but if you never learn to work effectively with iterators, you'll be stumped the moment you try to work in an environment where indexing isn't realistic (e.g. if you try to work in a functional langage, where linked lists are the de-facto standard collection and therefore indexing is too slow to be useful for most applications).
Jules
CC BY-SA 3.0
2017-07-15T18:13:07.950Z
`i` and `x` are the exact opposite of what I'd expect for element and index variabes.
Eric Duminil
CC BY-SA 3.0
2017-07-15T18:29:50.450Z
Comparing a foreach to a while loop rather than to a regular for loop is not particularly a fair comparison.
Alfred Thompson
CC BY-SA 3.0
2017-07-14T23:55:39.037Z
2017-07-15T00:11:19.693Z
2017-07-15T00:11:19.693Z
auden
<blockquote>
  <p><strong>Edit:</strong> 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:</p>
</blockquote>

<p>I personally dislike the <code>foreach</code> 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 <strong>AP Computer Science A</strong> curriculum.</p>

<pre><code> for (Type item : iterableCollection) {
      // Do something
 }
</code></pre>

<p>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?</p>

<p>I will put my own answer below alongside the others.</p>

CC BY-SA 3.0
2017-07-15T04:37:06.217Z
You learned in the procedural era, didn't you?
Loren Pechtel
CC BY-SA 3.0
2017-07-15T13:33:27.673Z
Remember, some languages have arrays with indexes that are not numeric - the associative array in PHP is like this, so database query results and json data.  To loop through an array of this type, using a for each style loop is required.  `foreach($array as $key=>$value)` - but then, you did specify for Java, so these reasons don't exist in your particular use case....
ivanivan
CC BY-SA 3.0
2017-07-15T20:16:10.340Z
I'd just like to say that for the past couple years I've been using languages that don't have a c-style for loop. I never missed it.
CAD97
CC BY-SA 3.0
2017-07-16T07:07:07.290Z
Can you share your reasons *why* you dislike it?
Bergi
CC BY-SA 3.0
2017-07-18T16:11:16.887Z
Yikes, I hope you're not suggesting you wouldn't teach students about the `foreach` loop if you weren't forced to by your curriculum!
Ben Aaronson
CC BY-SA 3.0
2018-02-04T04:38:38.063Z
@ivanian java has many constructs that you cannot iterate through with an index counter, including Maps, which are functionally the same as arrays indexed by objects. The foreach construct is very convenient for avoiding hard to track but simple words in looping.
pojo-guy
<programming><java><looping>
Teaching the tradeoffs of the foreach loop
# Teaching the tradeoffs of the foreach loop

(Asked by: username_0 on 2017-07-14)

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.

**Tags:** programming, java, looping

> **Comments:**
> **username_1**: You learned in the procedural era, didn't you?  
> **username_2**: Remember, some languages have arrays with indexes that are not numeric - the associative array in PHP is like this, so database query results and json data.  To loop through an array of this type, using a for each style loop is required.  `foreach($array as $key=>$value)` - but then, you did specify for Java, so these reasons don't exist in your particular use case....  
> **username_3**: I'd just like to say that for the past couple years I've been using languages that don't have a c-style for loop. I never missed it.  
> **username_4**: Can you share your reasons *why* you dislike it?  
> **username_5**: Yikes, I hope you're not suggesting you wouldn't teach students about the `foreach` loop if you weren't forced to by your curriculum!  
> **username_6**: @ivanian java has many constructs that you cannot iterate through with an index counter, including Maps, which are functionally the same as arrays indexed by objects. The foreach construct is very convenient for avoiding hard to track but simple words in looping.  

---

## 12 answers

### Answer by username_10 on 2017-07-14. Score: 28

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.

> **Comments:**
> **username_6**: Speaking as a Java programmer, not a teacher, I only use the old style loops when there is a clear benefit. The foreach loop can compile more efficiently, and as username_10 says they prevent common errors that beginners are prone to make, but also plague more experienced programmers who get a little lax.  

---

### Answer by username_12 on 2017-07-14. Score: 10

I think foreach loops are great, and are almost always preferred over for loops. While for loops are fundamental material and definitely should be covered, they're sort of infrequently used in practice -- when iterating, we almost always iterate over lists and other collective (and it's generally considered bad practice to modify a data structure you're iterating over anyways, so it's no big deal if we lose that -- see the recent trend towards functional programming and immutable data structures).

(After all, there's a reason why languages like Python basically got rid of for loops in favor of foreach loops! Generally, when you're looping, it's because you're looping over lists, sets, collections, or infinite generators.)

That said, it would probably be a bad idea to introduce foreach loops immediately. In the courses I help teach, we wait until we've introduced the following concepts first:

1. Using regular for loops
2. OOP
3. Using basic data structures (ArrayList, LinkedList, Stack, Queue, etc)

Once we hit that point, we typically do the following:

1. Start by talking about sets and maps (in a previous lesson).
2. Intentionally run into a limitation: if hash sets are inherently unordered, and the concept of getting the "i-th" element of a hashset is simply undefined, how do we iterate over it? This serves as a great motivator for why we need a new looping concept (if you introduce foreach loops earlier, students are likely to brush this off by treating as only a mildly more convenient form of a for loop, which is missing the point).
3. Rather then jumping into foreach loops, we detour by talking about iterators. Time permitting, we implement a basic one for an arraylist we previously wrote together in class -- the goal is to demystify each step.

   We have students use Scanners to do file IO/string parsing in previous assignments, so they usually get the hang of using iterators pretty quickly/find they have a good intuition for using iterators.

   If we're feeling really ambitious, we can discuss this lets us implement data structures that are infinitely long.
4. But of course, iterators are pretty clunky, so that serves as good motivation for the final part of the lesson: foreach loops. We introduce the notion of "syntactic sugar", and demonstrate how Java internally rewrites the foreach loop into a while loop using an iterator. (This helps demystify a lot of the "magic" of foreach loops for students).
5. We finish by talking about some of the limitations of foreach loops (e.g. you can't modify the collection you're iterating over) and discuss stylistically when you should use for loops vs iterators vs foreach loops.

   If you have time, this would also perhaps be a good place to discuss how it can be useful to intentionally *limit* what you can do in order to gain something in exchange. In this case, we exchange the ability to modify our data structure in exchange for cleaner and more readable code and the ability to iterate over a wider variety of data structures. This actually echos some of our earlier discussions on hashmaps/hashsets -- by removing "indexability", we were able to get faster lookups.

All of this usually takes about one hour-long lesson, assuming you've covered basic usage of maps and sets in a previous lesson.

Finally, to help reinforce the point, we start mandating that students use foreach loops whenever possible on their homework, and start deducting points if they use for loops in places where it's not the best option.

The very next homework assignment requires students to manipulate and iterate over sets and maps, so in practice it's almost impossible for students to lose points for this.


---

### Answer by username_13 on 2017-07-15. Score: 9

There is much discussion here about how a traditional `for` seems more powerful than a `foreach`, but a traditional `for` with sentinel value can only be used to iterate over an indexable collection. Data structure like sets and maps are prevalent, and iterating over them by index would be technically and conceptually absurd. (You've already outlined places where `for` is invaluable, but it's applicability is technically limited to only a few (granted, extremely common) types).

Furthermore, good code expresses intent, which is why we have types like 'bag' which may seem just like an inferior list/vector: if you have data which is conceptually unordered, then you are imposing a layer of complexity on the mapping between code and reality by using a outwardly ordered data structure (e.g. `ArrayList`)...

... `foreach` is about enumerating/iterating over collections, and expresses the intent *much* more clearly and succinctly than a traditional `for` loop, which is just a familiar and tidy way of expressing an equivalent while loop. `foreach` lets you exploit the `ICollection`, or `Iterable`, or `IEnumeable` abstraction, which is fundamental to reusable collection handling code (I'm a C#er, not sure what the Java interfaces are called).

Others have already detailed why `foreach` is great for maintainability (aside from expressing the intent of the code better, it's *so much harder* to get wrong, and even *easy* to get right), and I would agree/suggest that you should typically use a `foreach` whenever you can quickly work out how to do so. For example, if you need to keep track of the previous value in the loop (see username_10's answer), this is readable and easy enough to write in a `foreach` loop that the benefits of having a more general purpose piece of code (`foreach` will work on any collection) will be of sufficient value to eclipse any perceived greater clarity in the for loop.

I'll just add that even if you are throwing together code you don't expect other people to see, or to even look at yourself in the future, writing at a high level of abstraction helps to prevent errors, and gives your type system the best chance of catching mistakes for you. If you are just iterating over the values in a collection (which happens *a lot*) then use a `foreach` loop *because* it is less powerful: you've told the code that you don't want to modify the collection, now when you try to, your language can scream and shout at you (that's its job!).

*Just for reference, I'm a C#er who has done a lot of (C#) code-golf. I love traditional `for`-loops, and can surely read and write them quicker than most: both loops are applicable in many places in the real world; `foreach` usually wins out where they overlap.*

> **Comments:**
> **username_14**: Agreed, I just posted a comment myself about the ability of iterators to represent unindexable data and agree it's a really important point - iterators are a simpler interface that requires less of your data source, meaning they generally scale better. Likewise, the things iterators can't do are mostly language limits of Java (no tuples, no returning references to items in a list) rather than strict limitations of the concept themselves.  
> **username_10**: I note that I am _especially_ careful when I write code only for myself. Indentation, brace all, intention revealing names, ... All of it. I know that if it is just for me, I'll return to it later and don't want to have to de-obfuscate my own code. And I especially don't want to have to add braces to code that omitted it on an update. Get it right. Get it done.  

---

### Answer by username_10 on 2017-07-14. Score: 4

To do something like the following with foreach...
// Exercise 3:
for (int j = 1; j < myDoubles.size(); j++){
   if (myDoubles.get(j) < myDoubles.get(j-1))
        return false;
return true;

consider the following, expressed as a static method
public static boolean isSorted(ArrayList values){
    boolean first = true;
    Integer previous = Integer.MIN_VALUE;
    for(Integer value: values){
        if(first){
            first = false;
        } else {
            if (value < previous){
                return false;
            } 
        }
        previous = value;               
    }
    return true;
}

I won't try to argue that this is simpler, however it does illustrate some important techniques useful elsewhere. The processing of the first element is handled explicitly, often important to do. In the original for loop version it is handled by starting at 1, which is easy to miss. The other technique is the handing off of a current value to a previous reference. There are a couple of other simpler things here, such as MIN_VALUE (which isn't used, but avoids an uninitialized value - that will fail the < test also). A slight modification would work for Doubles, of course.

> **Comments:**
> **username_0**: I stand by the pedagogic usefulness of my example, though I will add yours into my future discussions of the  tradeoffs. If you add an extra int, then there are no limits on power, because you could also just add back in the missing sentinel value. But the complexity of the code rises, and the fact that you're not given a sentinel in the first place is still a limit of the form itself that you must work around. And without the additional variable, the sequential comparison is not possible.  
> **username_12**: @BenI: a third alternative you could bring up is implementing a helper function that transforms an iterable into an iterable of pairs and foreach over that. The syntax is still a bit clunky because Java had no built-in syntax for manipulating/destructuring types, but it would make the foreach approach clean again/visually similar to the for loop solution. It's perhaps cheating in the context of your exercise since we're not sticking with just foreach loops, but this would be a good opportunity to help students start thinking about iteration on a higher level.  
> **username_15**: See my comment on @BenI.'s answer: Using `java.util.Optional` makes this *much* simpler, because you don't need to have a special case to handle the first iteration (the different behaviour of `Optional.empty()` vs `Optional.as(value)` handles it for you). And this is, perhaps, an important point here: working in the `foreach` style requires a slightly different approach, and the tools to make that approach convenient have taken a while to get here (at least in Java... Optional types have been around for years in functional languages), but now they are it is critical to learn how to use them.  

---

### Answer by username_0 on 2017-07-14. Score: 3

Part 1
When I introduce the foreach loop, I do it the context of a lecture on ArrayLists and wrapper classes.  I first just kinda slip it in unannounced:
double total = 0.0;
for (double currentValue : myDoubles)
    total += currentValue;
System.out.println(total);

Then we turn to it and begin to break it apart a little.  I first compare it to
for (int j = 0; j < myDoubles.size(); j++){
    double currentValue = myDoubles.get(j);

.  But then I tell the students that there is a hidden limitation.  I want to see if they can spot it, and I provide them with three re-writing exercises (that are also practice exercises on the prior concepts) to help them find it:
// Exercise 1:
double total = 0.0;
for (int j = 0; j < myDoubles.size(); j++){
    total += myDoubles.get(j);

// Exercise 2:
for (double currentValue : myDoubles)
   total += currentValue;

// Exercise 3:
for (int j = 1; j < myDoubles.size(); j++){
   if (myDoubles.get(j) < myDoubles(get(j-1))
        return false;
return true;

When the last one turns out to be impossible, we discuss the limits imposed by not having a sentinel value.
Part 2
We revisit foreach loops later in the year when we deal with multi-dimensional arrays.  Towards the end of that lesson, they are given this task:

For some int[][] ma, fill every element with the value 3.

We discuss the standard for loop solution:
for (int y = 0; y < ma.length; y++)
    for (int x = 0; x < ma[y].length; x++)
        ma[y][x] = 3;

And then I bring them back to foreach with this pretty-looking thing:
for(int[] outer : ma)
    for(int x : outer)
        x = 3;

... which, of course, doesn't work at all. I ask the kids to pair up and try to figure out why before we all come back together to have a discussion.
This example brings us right to the heart of copy-by-value (and provides another chance for us to revisit references).  I consider the discussion over only when the students seem to understand why the nested foreach doesn't work, but this loop does:
for(int[] outer : ma)
    for(int x=0, x

> **Comments:**
> **username_14**: I think if you are going to talk about the limits, an interesting point to make is that Java's limited support for things like tuples make it harder to implement good solutions inside iterators. Python, for example, makes part 1 rather easy (`any(first < second) for (first, second) in zip(items[1:], items))`). Likewise, `C#`'s `ref` returns could be used to solve the second case (although they aren't, as far as I know). I think it's valuable to note that the iterator provides a lot of value but in some cases is too limited (by it's design in that language) to solve some problems.  
> **username_14**: Most importantly, it's increasingly common for programmers to have to deal with large amounts of data, and storing all of your data in memory isn't always possible. Traditional indexing `for` loops are generally useless when dealing with lazy data, and so understanding how to do things with iterators rather than indexing means your code can scale far more effectively.  
> **username_15**: "When the last one turns out to be impossible"... `Optional<Double> last = Optional.empty(); for (Double d2 : myDoubles) { if (last.map(d1 -> d2 < d1).orElse(false)) return false; last = Optional.of(d2); }`. Ok, it's a *little* harder to understand at first grasp than yours, but has the advantage that it's O(n) for all standard collection classes, whereas your version is O(n^2) for linked lists, and is also thread safe if `myDoubles` is a concurrent collection. And it promotes a way of thinking about the problem that is more generally useful and less fragile than working directly with indices.  
> **username_15**: (and yes, I do think these concepts are fundamental enough that they should be taught early enough that students looking at the `foreach` loop should already know about them: the "optional" container type, lambda functions, "map" functions on containers -- we think of them as advanced topics because they were introduced late to most of our popular languages, but the different way of thinking about problems they enable can make for much better code in many situations, and they should therefore probably be our first choice for tackling most problems, so why not teach them first?)  
> **username_16**: Oh. When I saw you talking about the limitations in the question the first one which came to mind is that you can't call `remove()` on the `Iterator`, but that doesn't seem to enter into your considerations at all. I see `for (Foo foo : foos) {` as sugar for `for (Iterator<Foo> it = foos.iterator(); it.hasNext(); ) { Foo foo = it.next();`, but all of the answers seem to be about iterating over arrays rather than collections.  

---

### Answer by username_17 on 2017-07-19. Score: 3

I don't think you should teach the `foreach` loop and then point out all of its "flaws" when compared to a traditional `for` loop. You should treat them both as tools, and different tools are used for different tasks. Maybe teach them a bit of the history (traditional `for` came first, then `foreach` was added in Java 5) and show them an example of when it would be best to use each.

Also note that you seem to be skipping over a third looping mechanism, which the `foreach` loop is based on: the `Iterator`.

Compare two tasks, like printing out every value in an `ArrayList` and removing all elements that match a certain criteria (for example, values that are less than 0). Show them how you'd do (or how it's not possible to do) each task in all **three** types of loop.

With the simple printing task, the `foreach` loop is perfect. Using a traditional `for` loop or an `Iterator` is probably overkill for this task. But with the task of removing elements, the `foreach` loop will throw an exception! If you're using a traditional `for` loop, you have to loop backwards or be very careful about which index you're looking at (otherwise you might skip elements). And an `Iterator` is probably best suited for this task.

The point is that everything in programming should be treated as a tool. A tool isn't inherently better or worse than other tools, it's just better suited for specific tasks. Talk about those tasks.


---

### Answer by username_18 on 2017-07-23. Score: 3

Addressing the subquestion regarding limitations of `foreach`:

I've been a reader for the AP Computer Science A exam since 2004. The most common mistake we see in student solutions regarding `foreach` loops deals with two important limitations:

* `foreach` loops lose any association between items in an ordered collection (e.g. array, `ArrayList`) and their indexes. If the core algorithm requires knowing the location of an item as well as its value (e.g. returning the index of an item in an `ArrayList`), `foreach` loops are usually inappropriate.
* `foreach` loops cannot modify the base collection while iterating over it. If the core algorithm requires changing the base collection, the `foreach` loop is inappropriate.

> **Comments:**
> **username_19**: Thank you for sharing your insight as an AP CS exam reader. I'll look for more of your answers.  
> **username_0**: Good points!  I'd also be extremely interested in your insights on [this](https://cseducators.stackexchange.com/questions/143/designing-rubrics-for-ap-computer-science-style-free-response-questions) question as well.  

---

### Answer by username_20 on 2017-07-14. Score: 2

You should definitely teach foreach loops. Why?

Foreach loops are the main type of loop in Python.
Python is the awesomest.
Therefore foreach loops are important.


All "joking" aside, foreach loops are super useful - I use them all the time. They're the difference between
x = 0
while x < len(list):
    print(list[x])
    x+=1

and
for i in list:
    print(i)

This illustrates a couple nice things about foreach loops:

Very short, clean code.
Less variables to keep track of - nice for any programmer, let alone novices.
Much easier to iterate through lists/arrays/dictionaries/strings or perform batch operations.
Allows you to introduce list comprehensions much more easily (what's a list comprehension but a condensed foreach loop?), and everyone knows list comprehensions are the best thing since sliced lists.
Very commonly used in awesome programming languages like Python. (Seriously, though, Python's pretty commonly used - best to be prepared for using it.)

> **Comments:**
> **username_15**: It should be noted that Python isn't the only language where the use of iterated loops is much more common than any other type, which is perhaps an important point: you can learn to work with indices rather than iterators in some environments, but if you never learn to work effectively with iterators, you'll be stumped the moment you try to work in an environment where indexing isn't realistic (e.g. if you try to work in a functional langage, where linked lists are the de-facto standard collection and therefore indexing is too slow to be useful for most applications).  
> **username_21**: `i` and `x` are the exact opposite of what I'd expect for element and index variabes.  
> **username_22**: Comparing a foreach to a while loop rather than to a regular for loop is not particularly a fair comparison.  

---

### Answer by username_7 on 2018-02-04. Score: 1

Ruby would be a really interesting language for you to work with, given your dislike of foreach loop.  It provides an good way to think about a for loop. In ruby, the for keyword does not exist. There's no way to actually create a for loop. But any collection (Enumerable) has a #each method, which iterates of the elements of the collection. For example:
words = ["apple", "car", "coffee", "document"]
words.each do |word|
  puts word
end
#=> apple
#=> car
#=> coffee
#=> document

To implement a traditional for loop, you need to iterate over a range (in ruby the a..b notation generates an Enumerable from a to b):
words = ["apple", "car", "coffee", "document"]
[0..3].each do |i|
  puts words[i]
end
#=> apple
#=> car
#=> coffee
#=> document

Which syntax makes more conceptual sense and is more readable? I'd certainly say the first one. It also will help students seperate the concept of a loop with the specific syntax for creating a loop.


---

### Answer by username_8 on 2020-01-26. Score: 1

There is no "limitation" or "tradeoff".

The point is, we express ideas at a given level of abstraction.

The "forall" is for ranging over the values in a collection.

The for(int i = 0; i < n; i++) etc is for ranging over numbers, that sometimes happen to be the valid indices in some array. Quite a different matter.

Use the appropriate level of abstraction. The for loop is not a limitation over the while loop, or goto+if constructs.

Edit: actually some colleagues don't want to teach the foreach, because it comes with a break when you want to leave it before its natural end, which happens rather frequently.

And, you know, break is somehow like goto, which is considered awful and definitely forbidden. Burn these heretics and their for each loop!


---

### Answer by username_9 on 2018-02-07. Score: 1

Don't forget to mention what information is not available when they choose between certain looping constructs:

foreach loops lose position data (index, relative locations (i and i-1, etc)
for(int i;;) loops lose the index variable (i) upon completion of the for loop

foreach loops are designed to work with collections & iterators.

See [Teaching the humble for loop](https://cseducators.stackexchange.com/questions/2632/teaching-the-humble-for-loop/4301#4301)

Also from a AP CS A exam perspective, the trap is usually that you don't have an index value. The advice I give to the students taking this exam is to avoid the foreach when writing exams because in the majority of cases they will require the index.

> **Comments:**
> **username_10**: I encourage you to fill out your answer. Short answers like this tend to get ignored, or worse. Help future readers draw the correct inferences that you see yourself.  
> **username_9**: Your students would need to be aware of the the issues around using iterators -- attempts to modify the underlying collection, copied elements, etc.  

---

### Answer by username_11 on 2017-07-18. Score: 0

I like this loop. A lot. You don't go out of bounds. It eliminates an important source of errors. I encourage its use when iterating through collections. I also ask students who make collections to implement Iterable so that they can use the collections `for` loop on their custom collection.


---

