<p>If I'm interpreting your question correctly you'd like real life examples that translate to code. Maybe something like the following. </p>

<ul>
<li><p>You want to drive or ride your bike to the ice-cream shop a few miles away. You don't know how far it is exactly but you will recognize it when you get there (while), <strong>VS</strong> You want to ride your bike 15 miles out and then return and you have an odometer on the bike (for)</p></li>
<li><p>You want to shoot baskets until you have made 100 attempts (for) <strong>VS</strong> You want to shoot baskets until you have made 50 successful shots (while). Outside the US, substitute <em>free kicks</em>. </p></li>
<li><p>You want to write a 15 page paper on looping in Java (for) <strong>VS</strong> You want to work on your "looping in Java" paper until you are satisfied with the result (while). </p></li>
<li><p>You want to boil potatoes until a fork can be easily inserted (while) <strong>VS</strong> You want to boil potatoes for 11 minutes (for).</p></li>
</ul>

<p>To translate these into code you need some <em>imagined</em> functions for the actual activities (<code>void boilPotatoes()</code>). </p>

<p>For some of them it is useful to discuss the empty case: you are already at the ice-cream shop, etc. For others, a discussion of "at least one iteration" might be useful to have. </p>

<p>If you want to include <code>foreach</code> in the game:</p>

<ul>
<li>You want to polish all of your mom's teacups (foreach) <strong>VS</strong> You want to polish her ten most valuable teacups (for) <strong>VS</strong> You want to polish teacups until you run out of polish (while). </li>
</ul>

CC BY-SA 3.0
2017-10-02T12:04:01.650Z
These don't look like console based tasks, they are 'human robot' tasks...
Sean Houlihane
CC BY-SA 3.0
2017-10-03T09:22:26.620Z
I'd interpret it differently: find good examples of for/while in concrete java applications, not "real life examples" which are not related to programming.
Michel Billaud
CC BY-SA 3.0
2017-10-02T11:47:59.397Z
2017-10-02T20:10:23.877Z
2017-10-02T20:10:23.877Z
Buffy
<p>typical <code>for</code> loop: loop over an interval. You can easily separate the control part (the successive values of the loop variable) and the calculations.</p>

<pre><code>for (float eur = 1; eur &lt;= 10; eur += 0.5) {
  float usd = eur * 1.17345;
  println(eur,"EUR is ", usd, " USD today");  // Processing
}
</code></pre>

<p>typical <code>while</code> loop</p>

<pre><code>float x = 2;
float epsilon = 0.001;

float a = x/2;   // approximation of square root

while(abs(a * a - x) &gt; epsilon) {
  a = (x/a + a) / 2;
}
println ("square root of", x, "is near", a);
</code></pre>

<hr>

<p>Two examples based on a common theme (financial calculations)</p>

<ul>
<li>print the table of composed interests over 10 years (loop with counter)</li>
<li>how many years does it take to double your capital at some interest rate (while not enough, etc)</li>
</ul>

CC BY-SA 3.0
2017-10-02T14:09:03.097Z
The first example is counterproductive. Students should be taught *not* to use floating point for types such as "money" which are inherently fixed-point decimal values.
Peter Taylor
CC BY-SA 3.0
2017-10-02T16:56:49.307Z
@PeterTaylor I agree you should teach them to use `java.math.BigDecimal` for real money calculations. The use of such objects in the `for` loop is left as a funny exercise to the reader.
Michel Billaud
CC BY-SA 3.0
2017-10-03T10:47:12.153Z
Actually, the first example is worse than that. Using floats in any counting situation can easily lead to a classic "off by one" error". You have to assume that 0.5 is exact (which it likely is) but other very similar situations will fail. Try to count by 0.2 for example, up to about 1000.0. (I don't know if that one actually fails, but some will). Just as in base 10, 1/3 isn't precisely representable, many things in base 2 are not.
Buffy
CC BY-SA 3.0
2017-10-03T11:24:45.553Z
And note that BigDecimal is _arbitrary precision_. But that isn't the same as _infinite precision_. Rounding happens. Good enough for money, but not for everything.
Buffy
CC BY-SA 3.0
2017-10-03T11:37:33.580Z
@buffy Of course it happens, and it has to, for money handling applications. The way it happens (precision, rounding mode) is defined by the MathContext http://docs.oracle.com/javase/8/docs/api/java/math/MathContext.html BTW who assumes the loop had to stop *exactly* on value 10 ?
Michel Billaud
CC BY-SA 3.0
2017-10-02T11:47:16.293Z
2017-10-02T12:00:33.980Z
2017-10-02T12:00:33.980Z
Michel Billaud
<p>Robots are certainly a good idea, but it sounds like you don't have any suitable hardware - I think simple hardware will give you plenty of opportunities and may also provide a different 'hook' for some of your students to become interested.</p>

<p>As an abstract level, <code>while</code> is a good fit for a background task as you identified. If you're using a console interface, you need to make up something along the lines of a screen saver (assuming there is no actual processing). Maybe the program can prompt for input, generate bad poetry, or draw some simple snake like animations. All the time, waiting for 'control' input. Alternatively, some experimental data collection if you have suitable I/O hardware.</p>

<p>Once you have the control, you want to demonstrate iteration with <code>for</code>. If you were using a micro:bit you could loop through a text string to display the result of some measurements. All you need is a set of data-points collected during the 'while' period. This could be a mash-up of the inputs generated by the user.</p>

<p>So, as a scenario:</p>

<pre><code>while (user has not said 'stop')
  Collect user inputs
  Generate random vogon poetry for the user
foreach(user input before stop)
  Congratulate user on writing the following work of art
  Repeat input with words mangled or re-ordered
</code></pre>

CC BY-SA 3.0
2017-10-02T09:30:10.537Z
2017-10-02T09:30:10.537Z
Sean Houlihane
<p>When looping through a collection, a <code>for</code> loop is best.  The collections <code>for</code> loops in Java, JavaScript and Python prevent you from accessing indices that are out of bounds. Most of the time, they are the right choice for traversing a collection.  The <code>for</code> loop is mostly a "definite loop."</p>

<p>The <code>while</code> loop is at its most useful when some indefinite number of iterations is required to perform a task.  For example, you might be asking a user for a specific type of output. IF the user fails to enter something valid,  you nag that user with prompts until he does the right thing.</p>

CC BY-SA 3.0
2017-10-10T04:16:53.877Z
Your `while` loop example is my `do while` example - always prompt the user once for input, and if they enter something invalid, continue to ask. And while your first example is good, as the question notes, these are very early programmers I'm teachings, without any sort of data structure beyond a variable yet.
cryptic_star
CC BY-SA 3.0
2017-10-09T01:41:10.650Z
2017-10-09T01:41:10.650Z
ncmathsadist
<p>So we know that we can use <code>for</code> and <code>while</code>, for all loops, but here are some simple rule as to when to use which one, to make programs easier to read, and understand.</p>

<p>If you can, use <code>foreach</code>: If iterating over a list (or other iterable type).
Note python calls foreach <code>for</code>. <code>foreach</code> can not always be used, but is much safer and easier to use, when iterating over things.</p>

<p>For experts, if you don't have <code>foreach</code>, then use <code>for</code> for bounded loops, that is those that could be implemented with a <code>foreach</code>, those that you know how many times you will loop (or the upper bound, in the case when you will break out early).</p>

<p>e.g.</p>

<pre><code>foreach item in list {
    process item
}

for (TypeOfItem item : list) {
    process item
}
</code></pre>

<p>However for beginners for loops, can be very confusing (I am not discussing foreach, or for in python). Therefore prefer while loops over for loops. But foreach loops over while. </p>

<p>See image from <a href="http://worrydream.com/LearnableProgramming/" rel="nofollow noreferrer">LearnableProgramming — Bret Victor</a>, showing program flow through a for loop.</p>

<p><a href="https://i.sstatic.net/TjgRQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TjgRQ.png" alt="enter image description here"></a></p>

<hr>

<p>In <code>C</code> like languages (C, C++, Java, C#, …), always use <code>for</code> in the form <code>for(int i=0; i&lt;n; i++)</code> (there may be some exceptions, but rare). So you are using <code>for</code> to construct a foreach, as the language does not have the higher level structure. (C# has <code>foreach</code>; C++ has library implementations; Java has foreach, but uses keyword <code>for</code>)</p>

CC BY-SA 3.0
2017-11-03T17:55:40.727Z
Since reading an article (now cited in my answer), I have changed my mind about the wisdom of teaching for loops to beginners.
ctrl-alt-delor
CC BY-SA 3.0
2017-10-02T09:14:45.897Z
This is not an example of engaging exercises, it is a tutorial on the syntax.
Sean Houlihane
CC BY-SA 3.0
2017-10-02T12:09:05.400Z
@SeanHoulihane “I'm looking for a set of concrete examples that illustrates good use cases of using a for vs a while loop” — so while not example, it is a rule, that can be taught and used to generate examples.
ctrl-alt-delor
CC BY-SA 3.0
2017-10-02T12:10:32.320Z
but we all know the rules, and if we wanted to learn about the rules, we'd be on SO...
Sean Houlihane
CC BY-SA 3.0
2017-10-02T08:55:27.803Z
2017-11-03T17:54:13.267Z
2017-11-03T17:54:13.267Z
ctrl-alt-delor
<p>You would know beforehand when the <code>for</code> loop would terminate, this is not clear in a <code>while</code> loop. I basically tell my students "if you know when it ends, it's a <code>for</code>". (Sure, one can construct pathological cases and there is always this <code>for (;;)</code>, but for basic understanding this issue <em>is</em> the crucial difference between <code>for</code> and <code>while</code>.)</p>

<p>As for examples:</p>

<ul>
<li>print all elements of this array is a <code>for</code>,</li>
<li>play so many rounds of tic-tac-toe until the human player quits: <code>while</code>.</li>
</ul>

<p>You might want to force them to convert <code>for</code> to <code>while</code> in an exercise and demostrate that the converse is not always possible. </p>

CC BY-SA 3.0
2017-10-04T02:56:42.900Z
Yes, I think these are generally good examples, but don't fit in the constraints laid out in the original question (e.g., my students don't yet know data structures).
cryptic_star
CC BY-SA 3.0
2017-10-04T23:07:31.153Z
Count numbers from 1 to 10? Next lession: `if`, `break`, `continue` and count only odd numbers and stop when encounter a cubic number? It feels hard to describe exactly the difference between `for` and `while` if there are no things that have no a priori known size. But user input, as hinted below, might be a good idea.
Oleg Lobachev
CC BY-SA 3.0
2017-10-05T01:28:32.130Z
Yes, we actually did many of those exercises earlier. I provided an answer to this question that I think did a decent job demonstrating the principle.
cryptic_star
CC BY-SA 4.0
2018-05-09T12:55:21.497Z
As you say, if there is a list or known (or determinable) number of things, use `for` or `foreach` (or equivalent) - loop through an array, iterate through POST values, etc.  If the required number of cycles is unknown (reading from a file, letting a user guess something, etc) then it is a `while` or `until` (or equivalents)
ivanivan
CC BY-SA 3.0
2017-10-02T17:50:18.423Z
2017-10-02T17:50:18.423Z
Oleg Lobachev
<p>Having looked through all the answers thus far the other day, I'm not entirely satisfied with any of them (I'll try to take the time later and go through to leave comments). However, for now, I'll post what I came up with for class.</p>

<p>First, I want to emphasize that these students only know what was mentioned above, no arrays/data structures, very little in terms of methods (just some of the ones for <code>String</code>), and little beyond the foundations of OOP (e.g., can't yet actually implement a class). Additionally, we have no hardware (or at least, not enough of it).</p>

<p>I went with a general goal of <code>String</code> processing, since they have done a fair amount of that. For illustrative purposes, we just printed items out to keep it simple, but discussed modifications for finding/replacing characters/patterns, other things you could do with this (we'll extend these tomorrow for nested loops). Note that they don't know <code>toCharArray()</code> and <code>split()</code> since we haven't yet discussed arrays, but the below examples replicate much of that functionality.</p>

<p>For a <code>for</code> loop, print each character of a <code>String</code> to its own line.</p>

<pre><code>String sentence = "Some example sentence";

for (int index = 0; index &lt; sentence.length(); ++index) {
    System.out.println(sentence.charAt(index));
}
</code></pre>

<p>For a <code>while</code> loop, print each word of a <code>String</code> to its own line.</p>

<pre><code>String sentence = "Some example sentence";

while(sentence.indexOf(' ') &gt;= 0) {
    System.out.println(sentence.substring(0, sentence.indexOf(' ')));

    sentence = sentence.substring(sentence.indexOf(' ') + 1, sentence.length());
}

System.out.println(sentence);
</code></pre>

<p>Yes, there are better ways of writing the above, but I wanted to start by emphasizing the use of the <code>while</code> loop, and then modifying it to handle that last word.</p>

<p>In general, this prompted a nice discussion of definite vs indefinite loops, and particularly the various shades of indefinite. One student pointed out that we could use <code>replaceAll()</code> to figure out the number of spaces in a <code>String</code> (i.e., replace all the spaces with nothing, compare lengths), but others thought that too much work to bother with before writing the loop.</p>

<p>Anyway, I would appreciate critiques of this for next time I teach CS1.</p>

CC BY-SA 3.0
2017-10-04T13:22:30.350Z
Something your answer alludes to that I'd not seen in the others, an imprecise example can be good if it results in a discussion.
Sean Houlihane
CC BY-SA 3.0
2017-10-04T15:42:57.630Z
@SeanHoulihane Could you clarify? I'm not sure I see what you mean.
cryptic_star
CC BY-SA 3.0
2017-10-04T15:47:00.683Z
You say 'there are better ways of writing the above' ... 'this prompted a nice discussion'. So you may not have meant that the discussion was about better ways of doing it, but if you're presenting some code to introduce a topic (rather than presenting a problem to be solved by the students, as I inferred in the Q), showing an example which can be improved upon is often constructive.
Sean Houlihane
CC BY-SA 3.0
2017-10-04T15:55:48.647Z
@SeanHoulihane Yes, I concur!
cryptic_star
CC BY-SA 3.0
2017-10-03T15:21:57.300Z
2017-10-03T15:21:57.300Z
cryptic_star
<p>I'm looking for a set of concrete examples that illustrates good use cases of using a <code>for</code> vs a <code>while</code> loop for beginners. I feel that I have a good grasp on teaching them about these loops in the abstract (e.g., definite vs indefinite loops, how we apply those concepts in life), but I would also like to show two (hopefully somewhat contextually related) motivating programming examples - one where a <code>for</code> loop is more appropriate, and one where a <code>while</code> loop is. Obviously either type of loop can be used in either instance, but I would like to prompt students to think more about when to use one versus the other. Coming up with two good examples that are illustrative of this point is eluding me.</p>

<p>To further limit the options available, students only know about console I/O, <code>String</code>/<code>int</code>/<code>double</code> types/variables, conditionals, and <code>while</code> loops. We are using Java.</p>

<p>So, for example, if I wasn't so focused on finding something that beginners could implement, I would show that a good use of a <code>while</code> loop is for a robot that should always be listening for voice input from a user; this is a good use, because we don't know when (i.e., after how many iterations) we will stop listening for voice input. I would then contrast this with a robot parsing through transcriptions of user voice input to identify keywords and respond to them. I've considered trying to translate this into console I/O, but the use of looping to continuously look for console input lends itself somewhat better to <code>do-while</code> loops, which we'll cover next.</p>

<p>I realize my question is likely a rehash of what was asked <a href="https://cseducators.stackexchange.com/questions/527/how-to-teach-which-loop-should-be-used">here</a>, but I wasn't happy with the answers. Answers on that post dealt more about the ordering of topics for teaching loops (e.g., <code>while</code> loops before <code>for</code> loops), or real-world motivating examples (e.g., while I'm not full, continue eating pizza). What I'm looking for is more in line with the later, but I would like to do something that translates well into code.</p>

CC BY-SA 3.0
2017-10-02T02:44:57.930Z
This question is specifically for motivating examples?
Ben I.
CC BY-SA 3.0
2017-10-02T03:08:57.370Z
@BenI. Yes, I am looking specifically for examples that I could show in code.
cryptic_star
CC BY-SA 3.0
2017-10-02T06:25:35.970Z
I don't think your description of the difference between `for` and `while` actually describes what happens in any reasonably popular language. These are just some used-to-be macros that due to historical reasons made their way into some programming languages. But there isn't really anything that warrants this particular number of kinds of loop keywords (some languages have more, some have less).
wvxvw
CC BY-SA 3.0
2017-10-02T08:35:39.903Z
What language? (python `for` in much like C# `foreach`)
ctrl-alt-delor
CC BY-SA 3.0
2017-10-02T08:38:47.340Z
The for loop (in C-ish languages) is here to give a clear separation between the control and the code to be executed at each turn. Then it leads to idiomatic forms, like the well-known  `for(int i=0; i<n; i++)`, or `for(char *p = str; *p; p++)` that every programmer recognizes without thinking. Can be done with `while`, but the `i++` part would be hidden far away. So the preference of the students for `for` over `while` relies on their ability to abstract the control part from the repeated part. Takes some time and exercises, with usual structures like "do sthg for x between min and max".
Michel Billaud
CC BY-SA 3.0
2017-10-02T09:31:05.203Z
You're constrained to use only console I/O, and no physical interfaces?
Sean Houlihane
CC BY-SA 3.0
2017-10-02T09:40:03.747Z
@SeanHoulihane I/O is all they know thus far, so yes. We'll move onto GUIs in a few weeks, which do naturally lend themselves to more `while` loops, but until then, we only have the console.
cryptic_star
CC BY-SA 3.0
2017-10-02T09:43:24.950Z
@cryptic_star Take a look here: http://www.the-tech-tutorial.com/top-10-command-line-linux-games/
Sean Houlihane
CC BY-SA 3.0
2017-10-02T09:56:14.527Z
Is the 'java' tag appropriate?
Sean Houlihane
CC BY-SA 3.0
2017-10-02T10:16:12.830Z
as in 'use this tag only if the use of the language would affect the question **significantly**'
Sean Houlihane
CC BY-SA 3.0
2017-10-02T12:00:44.600Z
@SeanHoulihane I added it because some of the previous commenters felt that language played a role. If there's a broader language tag that would be more appropriate, that's fine too.
cryptic_star
<java><introductory-lesson><looping><code-example>
Example for For vs While Loop (in Java)
# Example for For vs While Loop (in Java)

(Asked by: username_0 on 2017-10-01)

I'm looking for a set of concrete examples that illustrates good use cases of using a `for` vs a `while` loop for beginners. I feel that I have a good grasp on teaching them about these loops in the abstract (e.g., definite vs indefinite loops, how we apply those concepts in life), but I would also like to show two (hopefully somewhat contextually related) motivating programming examples - one where a `for` loop is more appropriate, and one where a `while` loop is. Obviously either type of loop can be used in either instance, but I would like to prompt students to think more about when to use one versus the other. Coming up with two good examples that are illustrative of this point is eluding me.

To further limit the options available, students only know about console I/O, `String`/`int`/`double` types/variables, conditionals, and `while` loops. We are using Java.

So, for example, if I wasn't so focused on finding something that beginners could implement, I would show that a good use of a `while` loop is for a robot that should always be listening for voice input from a user; this is a good use, because we don't know when (i.e., after how many iterations) we will stop listening for voice input. I would then contrast this with a robot parsing through transcriptions of user voice input to identify keywords and respond to them. I've considered trying to translate this into console I/O, but the use of looping to continuously look for console input lends itself somewhat better to `do-while` loops, which we'll cover next.

I realize my question is likely a rehash of what was asked [here](https://cseducators.stackexchange.com/questions/527/how-to-teach-which-loop-should-be-used), but I wasn't happy with the answers. Answers on that post dealt more about the ordering of topics for teaching loops (e.g., `while` loops before `for` loops), or real-world motivating examples (e.g., while I'm not full, continue eating pizza). What I'm looking for is more in line with the later, but I would like to do something that translates well into code.

**Tags:** java, introductory-lesson, looping, code-example

> **Comments:**
> **username_1**: This question is specifically for motivating examples?  
> **username_0**: @BenI. Yes, I am looking specifically for examples that I could show in code.  
> **username_2**: I don't think your description of the difference between `for` and `while` actually describes what happens in any reasonably popular language. These are just some used-to-be macros that due to historical reasons made their way into some programming languages. But there isn't really anything that warrants this particular number of kinds of loop keywords (some languages have more, some have less).  
> **username_3**: What language? (python `for` in much like C# `foreach`)  
> **username_4**: The for loop (in C-ish languages) is here to give a clear separation between the control and the code to be executed at each turn. Then it leads to idiomatic forms, like the well-known  `for(int i=0; i<n; i++)`, or `for(char *p = str; *p; p++)` that every programmer recognizes without thinking. Can be done with `while`, but the `i++` part would be hidden far away. So the preference of the students for `for` over `while` relies on their ability to abstract the control part from the repeated part. Takes some time and exercises, with usual structures like "do sthg for x between min and max".  
> **username_5**: You're constrained to use only console I/O, and no physical interfaces?  
> **username_0**: @SeanHoulihane I/O is all they know thus far, so yes. We'll move onto GUIs in a few weeks, which do naturally lend themselves to more `while` loops, but until then, we only have the console.  
> **username_5**: @username_0 Take a look here: http://www.the-tech-tutorial.com/top-10-command-line-linux-games/  
> **username_5**: Is the 'java' tag appropriate?  
> **username_5**: as in 'use this tag only if the use of the language would affect the question **significantly**'  
> **username_0**: @SeanHoulihane I added it because some of the previous commenters felt that language played a role. If there's a broader language tag that would be more appropriate, that's fine too.  

---

## 7 answers

### Answer by username_0 on 2017-10-03. Score: 1 | Accepted answer

Having looked through all the answers thus far the other day, I'm not entirely satisfied with any of them (I'll try to take the time later and go through to leave comments). However, for now, I'll post what I came up with for class.
First, I want to emphasize that these students only know what was mentioned above, no arrays/data structures, very little in terms of methods (just some of the ones for String), and little beyond the foundations of OOP (e.g., can't yet actually implement a class). Additionally, we have no hardware (or at least, not enough of it).
I went with a general goal of String processing, since they have done a fair amount of that. For illustrative purposes, we just printed items out to keep it simple, but discussed modifications for finding/replacing characters/patterns, other things you could do with this (we'll extend these tomorrow for nested loops). Note that they don't know toCharArray() and split() since we haven't yet discussed arrays, but the below examples replicate much of that functionality.
For a for loop, print each character of a String to its own line.
String sentence = "Some example sentence";

for (int index = 0; index < sentence.length(); ++index) {
    System.out.println(sentence.charAt(index));
}

For a while loop, print each word of a String to its own line.
String sentence = "Some example sentence";

while(sentence.indexOf(' ') >= 0) {
    System.out.println(sentence.substring(0, sentence.indexOf(' ')));

    sentence = sentence.substring(sentence.indexOf(' ') + 1, sentence.length());
}

System.out.println(sentence);

Yes, there are better ways of writing the above, but I wanted to start by emphasizing the use of the while loop, and then modifying it to handle that last word.
In general, this prompted a nice discussion of definite vs indefinite loops, and particularly the various shades of indefinite. One student pointed out that we could use replaceAll() to figure out the number of spaces in a String (i.e., replace all the spaces with nothing, compare lengths), but others thought that too much work to bother with before writing the loop.
Anyway, I would appreciate critiques of this for next time I teach CS1.

> **Comments:**
> **username_5**: Something your answer alludes to that I'd not seen in the others, an imprecise example can be good if it results in a discussion.  
> **username_0**: @SeanHoulihane Could you clarify? I'm not sure I see what you mean.  
> **username_5**: You say 'there are better ways of writing the above' ... 'this prompted a nice discussion'. So you may not have meant that the discussion was about better ways of doing it, but if you're presenting some code to introduce a topic (rather than presenting a problem to be solved by the students, as I inferred in the Q), showing an example which can be improved upon is often constructive.  
> **username_0**: @SeanHoulihane Yes, I concur!  

---

### Answer by username_6 on 2017-10-02. Score: 6

If I'm interpreting your question correctly you'd like real life examples that translate to code. Maybe something like the following.

* You want to drive or ride your bike to the ice-cream shop a few miles away. You don't know how far it is exactly but you will recognize it when you get there (while), **VS** You want to ride your bike 15 miles out and then return and you have an odometer on the bike (for)
* You want to shoot baskets until you have made 100 attempts (for) **VS** You want to shoot baskets until you have made 50 successful shots (while). Outside the US, substitute *free kicks*.
* You want to write a 15 page paper on looping in Java (for) **VS** You want to work on your "looping in Java" paper until you are satisfied with the result (while).
* You want to boil potatoes until a fork can be easily inserted (while) **VS** You want to boil potatoes for 11 minutes (for).

To translate these into code you need some *imagined* functions for the actual activities (`void boilPotatoes()`).

For some of them it is useful to discuss the empty case: you are already at the ice-cream shop, etc. For others, a discussion of "at least one iteration" might be useful to have.

If you want to include `foreach` in the game:

* You want to polish all of your mom's teacups (foreach) **VS** You want to polish her ten most valuable teacups (for) **VS** You want to polish teacups until you run out of polish (while).

> **Comments:**
> **username_5**: These don't look like console based tasks, they are 'human robot' tasks...  
> **username_4**: I'd interpret it differently: find good examples of for/while in concrete java applications, not "real life examples" which are not related to programming.  

---

### Answer by username_9 on 2017-10-02. Score: 1

You would know beforehand when the `for` loop would terminate, this is not clear in a `while` loop. I basically tell my students "if you know when it ends, it's a `for`". (Sure, one can construct pathological cases and there is always this `for (;;)`, but for basic understanding this issue *is* the crucial difference between `for` and `while`.)

As for examples:

* print all elements of this array is a `for`,
* play so many rounds of tic-tac-toe until the human player quits: `while`.

You might want to force them to convert `for` to `while` in an exercise and demostrate that the converse is not always possible.

> **Comments:**
> **username_0**: Yes, I think these are generally good examples, but don't fit in the constraints laid out in the original question (e.g., my students don't yet know data structures).  
> **username_9**: Count numbers from 1 to 10? Next lession: `if`, `break`, `continue` and count only odd numbers and stop when encounter a cubic number? It feels hard to describe exactly the difference between `for` and `while` if there are no things that have no a priori known size. But user input, as hinted below, might be a good idea.  
> **username_0**: Yes, we actually did many of those exercises earlier. I provided an answer to this question that I think did a decent job demonstrating the principle.  
> **username_10**: As you say, if there is a list or known (or determinable) number of things, use `for` or `foreach` (or equivalent) - loop through an array, iterate through POST values, etc.  If the required number of cycles is unknown (reading from a file, letting a user guess something, etc) then it is a `while` or `until` (or equivalents)  

---

### Answer by username_4 on 2017-10-02. Score: 0

typical for loop: loop over an interval. You can easily separate the control part (the successive values of the loop variable) and the calculations.
for (float eur = 1; eur <= 10; eur += 0.5) {
  float usd = eur * 1.17345;
  println(eur,"EUR is ", usd, " USD today");  // Processing
}

typical while loop
float x = 2;
float epsilon = 0.001;

float a = x/2;   // approximation of square root

while(abs(a * a - x) > epsilon) {
  a = (x/a + a) / 2;
}
println ("square root of", x, "is near", a);


Two examples based on a common theme (financial calculations)

print the table of composed interests over 10 years (loop with counter)
how many years does it take to double your capital at some interest rate (while not enough, etc)

> **Comments:**
> **username_7**: The first example is counterproductive. Students should be taught *not* to use floating point for types such as "money" which are inherently fixed-point decimal values.  
> **username_4**: @PeterTaylor I agree you should teach them to use `java.math.BigDecimal` for real money calculations. The use of such objects in the `for` loop is left as a funny exercise to the reader.  
> **username_6**: Actually, the first example is worse than that. Using floats in any counting situation can easily lead to a classic "off by one" error". You have to assume that 0.5 is exact (which it likely is) but other very similar situations will fail. Try to count by 0.2 for example, up to about 1000.0. (I don't know if that one actually fails, but some will). Just as in base 10, 1/3 isn't precisely representable, many things in base 2 are not.  
> **username_6**: And note that BigDecimal is _arbitrary precision_. But that isn't the same as _infinite precision_. Rounding happens. Good enough for money, but not for everything.  
> **username_4**: @buffy Of course it happens, and it has to, for money handling applications. The way it happens (precision, rounding mode) is defined by the MathContext http://docs.oracle.com/javase/8/docs/api/java/math/MathContext.html BTW who assumes the loop had to stop *exactly* on value 10 ?  

---

### Answer by username_5 on 2017-10-02. Score: 0

Robots are certainly a good idea, but it sounds like you don't have any suitable hardware - I think simple hardware will give you plenty of opportunities and may also provide a different 'hook' for some of your students to become interested.
As an abstract level, while is a good fit for a background task as you identified. If you're using a console interface, you need to make up something along the lines of a screen saver (assuming there is no actual processing). Maybe the program can prompt for input, generate bad poetry, or draw some simple snake like animations. All the time, waiting for 'control' input. Alternatively, some experimental data collection if you have suitable I/O hardware.
Once you have the control, you want to demonstrate iteration with for. If you were using a micro:bit you could loop through a text string to display the result of some measurements. All you need is a set of data-points collected during the 'while' period. This could be a mash-up of the inputs generated by the user.
So, as a scenario:
while (user has not said 'stop')
  Collect user inputs
  Generate random vogon poetry for the user
foreach(user input before stop)
  Congratulate user on writing the following work of art
  Repeat input with words mangled or re-ordered


---

### Answer by username_8 on 2017-10-09. Score: 0

When looping through a collection, a `for` loop is best. The collections `for` loops in Java, JavaScript and Python prevent you from accessing indices that are out of bounds. Most of the time, they are the right choice for traversing a collection. The `for` loop is mostly a "definite loop."

The `while` loop is at its most useful when some indefinite number of iterations is required to perform a task. For example, you might be asking a user for a specific type of output. IF the user fails to enter something valid, you nag that user with prompts until he does the right thing.

> **Comments:**
> **username_0**: Your `while` loop example is my `do while` example - always prompt the user once for input, and if they enter something invalid, continue to ask. And while your first example is good, as the question notes, these are very early programmers I'm teachings, without any sort of data structure beyond a variable yet.  

---

### Answer by username_3 on 2017-10-02. Score: -2

So we know that we can use for and while, for all loops, but here are some simple rule as to when to use which one, to make programs easier to read, and understand.
If you can, use foreach: If iterating over a list (or other iterable type).
Note python calls foreach for. foreach can not always be used, but is much safer and easier to use, when iterating over things.
For experts, if you don't have foreach, then use for for bounded loops, that is those that could be implemented with a foreach, those that you know how many times you will loop (or the upper bound, in the case when you will break out early).
e.g.
foreach item in list {
    process item
}

for (TypeOfItem item : list) {
    process item
}

However for beginners for loops, can be very confusing (I am not discussing foreach, or for in python). Therefore prefer while loops over for loops. But foreach loops over while. 
See image from LearnableProgramming — Bret Victor, showing program flow through a for loop.


In C like languages (C, C++, Java, C#, …), always use for in the form for(int i=0; i (there may be some exceptions, but rare). So you are using for to construct a foreach, as the language does not have the higher level structure. (C# has foreach; C++ has library implementations; Java has foreach, but uses keyword for)

> **Comments:**
> **username_5**: This is not an example of engaging exercises, it is a tutorial on the syntax.  
> **username_3**: @SeanHoulihane “I'm looking for a set of concrete examples that illustrates good use cases of using a for vs a while loop” — so while not example, it is a rule, that can be taught and used to generate examples.  
> **username_5**: but we all know the rules, and if we wanted to learn about the rules, we'd be on SO...  
> **username_3**: Since reading an article (now cited in my answer), I have changed my mind about the wisdom of teaching for loops to beginners.  

---

