Answers.Body: <p>I know I am very late to this party (and this idiom), but..</p>
  <p>The trick to teaching loops is pink hippos.</p>
  <p>There are five basic parts to a loop.</p>
  <ol>
  <li>Control Init (initialize the control variable)</li>
  <li>Loop Back Spot (a stupid name for the place the code jumps back to)</li>
  <li>Work (what you are repeating in the loop)</li>
  <li>Control Step (changing the loop control variable)</li>
  <li>Exit Check (checking the exit condition and jumping back as needed)</li>
  </ol>
  <p>Take a for loop (java for example)</p>
  <pre><code>  for (int ii = 2; ii &lt; 20; ii = ii + 2)
       System.out.println(ii);
  </code></pre>
  <p>with the parts labeled:</p>
  <pre><code>  &lt;loop back spot&gt; for (&lt;control init&gt;; &lt;exit check&gt;; &lt;control step&gt;) 
                          &lt;work&gt;
  </code></pre>
  <p>To demonstrate this in class I take out of large jar with 30 little pink hippos and write the five parts left to right across the board.  I then have five students come up to the front of the class room and stand under each of the loop parts. The one under the control step gets the jar of hippos.</p>
  <p>I then have a sixth student join the group at the front as the computer to run the code. The computer student receives one hippo at the start from the first student. That students job is done. The computer student then moves right passing the loop spot to the student at work. The student standing there then rights number of hippos the computer student is holding on the board.  The exit check student then evaluates the total hippos and gets to declare if the computer student is done. Not enough hippos! Go back to the loop back spot. Continue with the computer student having to hang onto an increasingly hilarious number of hippos. As this is taking place I'm pointing out the order that things happen, and important details like you will never have a value outside the range while inside the for loop.</p>
  <p>The important points are made, and the students have a clear visual to hang the somewhat esoteric idea onto.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-05-12T03:27:30.997Z
Answers.Text: Your loop back spot appears before the `for` declaration.  Why?
Answers.UserDisplayName: Ben I.
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-05-12T11:55:26.867Z
Answers.Text: The loop back spot is the for declaration.  Hard to show using text. When I'm explaining this in class I simply write a 2 and draw an arrow pointing at for.
Answers.UserDisplayName: codingCat
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-05-11T15:40:20.763Z
Answers.LastActivityDate: 2022-05-11T15:40:20.763Z
Answers.UserDisplayName: codingCat
Answers.Body: <p>Show then how the loop can be unfolded into a while loop:</p>
  <pre class="lang-c prettyprint-override"><code>int i = 0 // Step 1
  while (i&lt; 100) { // Step 2
      // Do something
      i++ // Step 3
  }
  </code></pre>
  <p>Explain that the order is derived from that unfolding.</p>
  <p>You could start out by only teaching while loops, forcing them to make these while loops with iterators, then showing that for loops are a condensed of those while loops with incrementing variables.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T01:34:49.990Z
Answers.Text: …and be prepared for the question "*Why should we use `for` loops instead of `while` loops when they're doing equivalent things, what's their **advantage**?*"
Answers.UserDisplayName: Bergi
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T01:35:51.150Z
Answers.Text: @Bergi You're telling the compiler what you want more clearly, allowing more optimization, and they simply take up less space and look neater.
Answers.UserDisplayName: thesecretmaster
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T01:45:11.063Z
Answers.Text: @thesecretmaster "Required to tell the compiler…" has never been a good reason. And I can only hope that the syntax choice does not affect the optimiser at all. The point is that they are easier to understand *for the programmer(s)* that have to read them. The iteration variable is (supposed to be) initialised and modified only in that single line, which makes for a an easily recognisable pattern and correct code where the update step is not forgotten. It also works with `continue;`
Answers.UserDisplayName: Bergi
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T13:51:26.083Z
Answers.Text: @Bergi Keeping the loop control variable in the `for` scope is a practical advantage as well.  The more correct "expansion" of a `for` loop would be: `{int i = 0; while(i < 100){++i;}}`.
Answers.UserDisplayName: IllusiveBrian
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-15T14:24:35.310Z
Answers.Text: @IllusiveBrian creation of the loop variable inside the `for(` statement wasn't possible until C99 allowed it.
Answers.UserDisplayName: Ruslan
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-15T17:50:15.630Z
Answers.Text: For loops do not optimise better than while loops (at least in gcc, clang and visual studio in C and C++). Arguments about easier to read code are sensible.
Answers.UserDisplayName: Chris Jefferson
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-15T19:28:50.913Z
Answers.Text: Won't this lead to teaching the Duff's device? That's not a path I'd recommend with students this fresh.
Answers.UserDisplayName: Mast
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-16T21:07:17.817Z
Answers.Text: I would like to add that, even though the while and for loops may be the same, in practical terms I would favor new programmers using the for loop, as it makes it much less likely to accidentally produce an infinite loop.
Answers.UserDisplayName: bytepusher
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-02-07T10:33:21.997Z
Answers.Text: About the cliché "for loop are syntactical sugar around while", it must be noted that the C for-loop was present already present in  B https://www.thinkage.ca/english/gcos/expl/b/manu/manu.html#Section5_7_4 together with a `forever` loop which is leaved by break or goto. So the while loop is a shortcut for   `forever {  if (! condition) break; .... }` if you are sugar addicted.
Answers.UserDisplayName: Michel Billaud
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-02-09T07:56:52.617Z
Answers.Text: And, actually, `while(cond) instr` is syntactic sugar around the special case `for(;cond;) instr;` as it preserves the meaning of a `continue` statement, not the other way. The fact is, our opinions about which is more fundamental may be biased when we prevously taught Pascal where there is no equivalent to the C-like for loop.
Answers.UserDisplayName: Michel Billaud
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-14T10:13:58.763Z
Answers.Text: @Bergi: "When you've dealt with iterative code for years, no matter which iteration is used, you [no longer see all of the code](https://78.media.tumblr.com/f8b9a8f9209c1220b0876a9ead23f353/tumblr_oylvu4FbMc1weu5xbo1_500.gif), you're only going to be looking at the important bits: initialization, evalutation to loop again, and how to change the evaluation with every loop that  is executed. The `while` syntax separates these bits and keeps them far away (unless the `while` body is trivially small, which it won't be in the real world), but the `for` keeps those things together, visually."
Answers.UserDisplayName: Flater
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-05-23T21:57:03.287Z
Answers.Text: There is a difference in this while loop: the loop variable has scope beyond the end of the loop.
Answers.UserDisplayName: ncmathsadist
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2017-07-13T21:15:21.673Z
Answers.LastActivityDate: 2020-10-05T22:17:12.710Z
Answers.LastEditDate: 2020-10-05T22:17:12.710Z
Answers.UserDisplayName: thesecretmaster
Answers.Body: <p>I know I'm coming late to this party but this is a really good question and I think it deserves a really good treatment.</p>
  <p>The original <code>for</code> loop, the one with the semicolons in it, is amazingly flexible, powerful, and confusing as all get out. It is seldom taught well, it is a very easy place for bugs to hide, and it is not going away.</p>
  <p>To master it you must learn the 1,   2, 4, 3,   2, 4, 3 pattern the OP mentioned. You must burn it into your soul. You must burn it into the souls of your students. The question is, how?</p>
  <p>The best way is to actually see it. To watch it happen. Unfortunately debugging tools often insist on highlighting the entire line.</p>
  <p><a href="https://i.sstatic.net/4tVJT.png" rel="noreferrer"><img src="https://i.sstatic.net/4tVJT.png" alt="debugger highlighting the full line" /></a></p>
  <p>Can you tell if <code>i</code> is about to be initialized, tested, or incremented here? Debugger highlighting is often useless for teaching or debugging the classic for loop.</p>
  <p>However, there is a way around that problem. The c style languages all have a feature that lets us work around this debugger limitation. Whitespace. Whitespace is meaningless in these languages. You can take advantage of that.</p>
  <p>So long as you're willing to explain that this:</p>
  <pre class="lang-java prettyprint-override"><code>for(int i=0; i&lt;10; i++) {
      System.out.println(i);
  }
  </code></pre>
  <p>will do the same thing as this:</p>
  <pre class="lang-java prettyprint-override"><code>for(
          int i=0; 
          i&lt;10; 
          i++
  ) {
      System.out.println(i);
  }
  </code></pre>
  <p>then you can show them this:</p>
  <p><a href="https://i.sstatic.net/2K5ny.gif" rel="noreferrer"><img src="https://i.sstatic.net/2K5ny.gif" alt="debugger single-stepping for-loop parts" /></a></p>
  <p>Do that, and rather than just explaining, you are showing them how this works, you are teaching them how to debug it themselves when they get confused by it.</p>
  <p>Now sure <a href="//softwareengineering.stackexchange.com/a/331680/131624">the multiline style</a> isn't popular with for loops but the students certainly don't have to turn in code that looks like that. It's just a form to use while testing because our debugging tools aren't yet smart enough to highlight only the relevant parts of a line.</p>
  <p>I've changed the speed and rhythm I use as I click. That's no accident. I'm using that to emphasize the starting and ending parts of each iteration. Students should not only feel like they can predict this. They should feel like they can use the debugger to re-teach themselves this pattern quickly if they ever need to.</p>
  <p>Consider a cascading style that retains column position for those more visually oriented:</p>
  <p><a href="https://i.sstatic.net/UB41P.gif" rel="noreferrer"><img src="https://i.sstatic.net/UB41P.gif" alt="same as last, but for-loop parts stay in the column they would have if it was a single line" /></a></p>
  <p>Now that's just the start of understanding loops. Writing <a href="//softwareengineering.stackexchange.com/q/315964/131624">correct, readable, efficient loops</a> is a whole other issue that this answer hardly does justice to.</p>
  <p>A lot of bugs hide right here. Don't undersell how worthy this is of close study.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-02-07T12:55:01.093Z
Answers.Text: You may be late to our "party" and I haven't noticed you here before, but you are giving some great answers. I'd offer you a party hat if I had one. Oh, I do, +1.
Answers.UserDisplayName: Buffy
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-02-07T14:30:59.050Z
Answers.Text: @Buffy hehe, thank you. This isn't my usual haunt but I can't resist a good question.
Answers.UserDisplayName: candied_orange
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-02-08T13:28:39.923Z
Answers.Text: This just might be the most useful answer I've seen in the last 3 months.
Answers.UserDisplayName: ItamarG3
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-02-08T21:47:41.920Z
Answers.Text: A nice solution and in the "video" you made it even better than in the "code", as I think the "video" has a better indentation.
Answers.UserDisplayName: Ola Ström
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-02-08T22:01:18.507Z
Answers.Text: @OlaStröm thank you. I realized the advantage of that form late and wanted to tack it on. After decades at this I'm still learning new tricks : )
Answers.UserDisplayName: candied_orange
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-02-13T15:23:29.617Z
Answers.Text: Wow--what a great suggestion for demonstrating a for loop.
Answers.UserDisplayName: Onorio Catenacci
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-22T01:01:56.060Z
Answers.Text: This is a nifty idea, but some IDEs can't highlight the distinct parts of the for-loop, even when split into separate lines in the source file. For example, I tried this in the Dev-C++ debugger and it only highlights the initializer part on any interation.
Answers.UserDisplayName: Daniel R. Collins
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-22T01:28:38.590Z
Answers.Text: @DanielR.Collins consider filing a bug. Feel free to link them to this answer to demonstrate the desired behavior. Wish all debuggers highlighted for loops correctly, regardless of line breaks.
Answers.UserDisplayName: candied_orange
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-22T02:07:44.707Z
Answers.Text: @candied_orange: This open-source IDE doesn't have support like that.
Answers.UserDisplayName: Daniel R. Collins
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-10-22T12:33:08.367Z
Answers.Text: @DanielR.Collins consider using an IDE that has support. Or, since it’s open source, supporting it yourself.
Answers.UserDisplayName: candied_orange
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-05-23T08:27:57.277Z
Answers.Text: What we really need is debuggers to learn that a single line of code can contain several independent items (statements).
Answers.UserDisplayName: David Balažic
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-02-07T09:04:33.953Z
Answers.LastActivityDate: 2020-10-06T03:17:15.550Z
Answers.LastEditDate: 2020-10-06T03:17:15.550Z
Answers.UserDisplayName: candied_orange
Answers.Body: <p>Theoretically, I teach the while loop first. Others have already explained how and why, but I'll go ahead with an example:</p>
  <pre class="lang-c prettyprint-override"><code>void showRating( int rating )
  {
      int i = 0;
      while ( i &lt; rating )
      {
          putchar( '*' );
          ++i;
      }
      putchar( '\n' );
  }
  </code></pre>
  <p>Some of the examples will be better expressed as for loops, and that's where I introduce the for loop, as a way of containing the essential elements in a concise construct. I might ask what happens if I forget to increment <em>i</em>:</p>
  <pre class="lang-c prettyprint-override"><code>void showRating( int rating )
  {
      int i = 0;
      while ( i &lt; rating )
      {
          putchar( '*' );
      }
      putchar( '\n' );
  }
  </code></pre>
  <p>And we compile it and run it.</p>
  <p>Then I show how the for loop might help us not forget the counter:</p>
  <pre class="lang-c prettyprint-override"><code>void showRating( int rating )
  {
      int i;
      for ( i = 0; i &lt; rating; ++i )
      {
          putchar( '*' );
      }
      putchar( '\n' );
  }
  </code></pre>
  <p>Too often, people think first of counting when they think of loops, and that's why they jump to the for loop first. But the C for loop is not really the counted loop that BASIC has led us to believe it is. And the English grammar for the word is not limited to counting, either.</p>
  <p>So I'll throw some for loops in that don't strictly count.</p>
  <p>I also teach the pun on forever that used to be the standard flag for an indeterminate loop:</p>
  <pre class="lang-c prettyprint-override"><code>for( ;; )
  </code></pre>
  <p>I'm likely to teach the post-test do ... while loop after having shown an indeterminate loop with a break at the end:</p>
  <pre class="lang-c prettyprint-override"><code>for ( ;; )
  {
      /* Always executes once. */
      if ( condition ) break;
  }
  </code></pre>
  <p>Now I would want to use something concrete here so I can show that it really always executes once, but I don't have time to make something up today.</p>
  <p>Then I can show them the do .. while loop:</p>
  <pre class="lang-c prettyprint-override"><code>do
  {
      /* Always executes once. */
  } while ( !condition );
  </code></pre>
  <p>Somewhere along in here I'll introduce the faux style thing about bracket placement and warn them not to argue with the managers about where to place them.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2017-07-14T06:31:05.473Z
Answers.LastActivityDate: 2020-10-05T22:17:24.873Z
Answers.LastEditDate: 2020-10-05T22:17:24.873Z
Answers.UserDisplayName: Joel Rees
Answers.Body: <p>It's about setting boundary conditions first. Provide them with a more concrete example, like filling a glass of milk. You kind of need a glass or container (let me know the next time you pour milk right on the counter) and that glass is some amount full. We'll just treat it as empty. Then, you stop filling the glass when it's full (or half full or whatever), unless you want milk everywhere.</p>
  <p>Within those boundary conditions, you pour the milk jug. That is, mentally, you're thinking (in not so many terms):</p>
  <pre><code>repeat following until checks make you stop pouring milk
  check: fullness of glass
  check: how close the fullness is to the wanted end fullness
  add some milk
  </code></pre>
  <p>That's exactly how a for loop thinks. It needs your conditions <em>first</em>, and then what you want to repeat while those conditions are true. (Yes, <em>while</em> - just like a while loop. I personally agree with thesecretmaster in that it makes a lot of sense to introduce while loops before for loops.) As you're pouring, you're constantly rechecking the level of the milk - &quot;updating&quot; a variable in your head as you act. So, if you were asking a computer to fill a glass of milk:</p>
  <pre class="lang-c prettyprint-override"><code>import milk
  for (float glassFullness = 0; glassFullness &lt; 1; glassFullness+=0.1) {
      milk.Fill()
  }
  </code></pre>
  <p>That could, of course, also be written</p>
  <pre class="lang-c prettyprint-override"><code>import milk
  float glassFullness = 0;
  while (glassFullness &lt; 1) {
      milk.Fill()
      glassFullness+=0.1
  }
  </code></pre>
  <p>They're doing the same things; the for loop is just a condensed version.</p>
  <p><strong>Tl;dr: a for loop looks for the boundary conditions, and then does what it needs to do, rechecking with a redefined variable accounting for the change that has been made. You input what change needs to be made to the variable to account for the action.</strong></p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2017-07-13T23:12:10.047Z
Answers.LastActivityDate: 2020-10-06T03:16:30.680Z
Answers.LastEditDate: 2020-10-06T03:16:30.680Z
Answers.UserDisplayName: auden
Answers.Body: <p><strong><em>tl;dr</em>–</strong>  A <code>for</code> loop is just a <code>while</code> loop that has extra slots for a pre-loop statement and a post-loop-run statement.  Since they're pretty much the same thing just written differently, a <code>for</code> loop is best understood as <a href="https://en.wikipedia.org/wiki/Syntactic_sugar" rel="nofollow noreferrer">syntactic sugar</a> that's useful when it increases the readability of the code.</p>
  <p>Sometimes new programmers are worried about performance, thinking that syntactic sugar might be less efficient.  That's not the case; the compiler really doesn't care how you write these loops, it's all the same to it.  So, students should be told to just write whichever's cleaner in the current context.</p>
  <p><strong>Homework/test question idea:</strong>  Have students convert a <code>for</code> loop into an equivalent <code>while</code> loop, or a <code>while</code> loop into an equivalent <code>for</code> loop.</p>
  <hr />
  <h3>Mapping between <code>for</code> and <code>while</code>.</h3>
  <p>The <code>for</code> loop:</p>
  <pre class="lang-c prettyprint-override"><code>for (prestatement; condition; poststatement)
  {
      // loop body
  }
  </code></pre>
  <p>is equivalent to the <code>while</code> loop:</p>
  <pre class="lang-c prettyprint-override"><code>{
      prestatement;
      while (condition)
      {
          // loop body
          poststatement;
      }
  }
  </code></pre>
  <p>, where:</p>
  <ul>
  <li><p><code>prestatement</code> is an executable statement that happens only once, before the loop starts.</p>
  <ul>
  <li>If omitted, then the loop just doesn't do anything extra before starting.</li>
  </ul>
  </li>
  <li><p><code>condition</code> is a <code>Boolean</code> expression that's evaluated at the start of each loop execution, breaking if <code>false</code>.</p>
  <ul>
  <li>If omitted, then there's no break check there.</li>
  </ul>
  </li>
  <li><p><code>poststatement</code> is an executable statement that happens after the end of each loop execution.</p>
  <ul>
  <li>If omitted, then the loop just doesn't do anything extra after each execution.</li>
  </ul>
  </li>
  </ul>
  <hr />
  <h3>Note on scope.</h3>
  <p>Even though</p>
  <pre class="lang-c prettyprint-override"><code>    int i = 0;
      int i = 0;
  </code></pre>
  <p>is illegal code because we can't declare <code>i</code> twice in the same scope,</p>
  <pre class="lang-c prettyprint-override"><code>{
      int i = 0;
  }
  {
      int i = 0;
  }
  </code></pre>
  <p>is legal because both <code>i</code>'s are in different scopes.</p>
  <p>This scoping issue is why we have the <code>while</code> statement above wrapped in extra <code>{}</code>'s, since the <code>prestatement</code> belongs in that scope.</p>
  <hr />
  <h3>Note on <code>continue</code>.</h3>
  <p>The keyword <code>continue</code> can <code>goto</code> the end of a loop's body.</p>
  <p>We can rewrite this behavior more explicitly:</p>
  <ol>
  <li><p>Make the implicit-label explicit by writing it out.</p>
  </li>
  <li><p>Rewrite <code>continue;</code> as <code>goto [label's name];</code>.</p>
  </li>
  </ol>
  <p>For example:</p>
  <pre class="lang-c prettyprint-override"><code>for (long i=0; i &lt; 1000; ++i)
  {
      if (i % 8 == 0) { continue; }
      //  rest of body
  }
  </code></pre>
  <p>becomes</p>
  <pre class="lang-c prettyprint-override"><code>for (long i=0; i &lt; 1000; ++i)
  {
      if (i % 8 == 0) { goto end_of_body; }
      //  rest of body
  end_of_body:
  }
  </code></pre>
  <p>If we then rewrite this as a <code>while</code> loop, it'd be</p>
  <pre class="lang-c prettyprint-override"><code>{
      long i = 0;
      while (i &lt; 1000)
      {
          if (i % 8 == 0) { goto end_of_body; }
          //  rest of body
  end_of_body:
          ++i;
      }
  }
  </code></pre>
  <p>That said, generally <code>goto</code> and related mechanisms (e.g., <code>continue</code>) are discouraged.  Presumably students ought to understand how they work, though it's generally best to avoid new usage.</p>
  <hr />
  <h3><code>for</code> loops can omit parts.</h3>
  <p>Might seem weird at first glance, but</p>
  <pre class="lang-c prettyprint-override"><code>for (;;) { }
  </code></pre>
  <p>is actually perfectly legal code!  Since it omits a <code>break</code> condition and doesn't do anything, it's basically an infinite loop that runs forever without doing anything.</p>
  <p>In C#, it doesn't consume CPU time, but it also blocks the thread from progressing.  For example,</p>
  <pre class="lang-c prettyprint-override"><code>for (;;) { }    //  Infinite loop
  foo();          //  Never happens because the above loop never ends
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-11-20T02:34:02.870Z
Answers.Text: @MichelBillaud: Good point, I should clarify the issue with `continue`.  Don't get me wrong, it's still just syntactic sugar, but probably ought to clarify that `continue` targets the spot after `//  loop body` in the translation.
Answers.UserDisplayName: Nat
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-11-20T07:09:33.670Z
Answers.Text: In C, control structures are mostly macros trying to hide some gotos under the carpet. But don't tell that to students.
Answers.UserDisplayName: Michel Billaud
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-19T19:48:38.823Z
Answers.Text: Not only syntactical sugar around a `while` loop, as the `continue` statement of the `while` loop skips the "poststatement".
Answers.UserDisplayName: Michel Billaud
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2017-07-14T17:18:14.863Z
Answers.LastActivityDate: 2020-11-20T03:29:35.483Z
Answers.LastEditDate: 2020-11-20T03:29:35.483Z
Answers.UserDisplayName: Nat
Answers.Body: <p>I teach <code>for</code> loops using the following pseudocode, which we then translate into actual code:</p>
  <pre class="lang-c prettyprint-override"><code>for (initialization; condition; update)
  {
      statement;
  }
  </code></pre>
  <p>This logic helps justify why the order goes <code>1, 2, 4, 3</code> to start. I explain it as follows: a variable can only be initialized once so it happens first and never again. After that the variable is tested against the condition. If the condition is true, then the code proceeds to the statement. Only then will it reach update. If the first conditional test fails, the update code is never executed.</p>
  <p>I have found that <code>for</code> loops are one of the few constructs that benefit most directly from drawing a flowchart. Using the visual diagram will help this logic become clearer.</p>
  <p>Another benefit of teaching the <code>for</code> loop this way is that it becomes trivial to translate it into <code>while</code> or <code>do-while</code> with the same pseudocode constructs.</p>
  <pre class="lang-c prettyprint-override"><code>// while loop
  initialization;
  while (condition)
  {
      statement;
      update;
  }
  
  // do-while loop
  initialization;
  do
  {
      statement;
      update;
  } while (condition);
  </code></pre>
  <p>Once I do this, I can focus on each of these four parts, so students understand the different components that make up a loop regardless of the structure thereof.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T15:31:54.893Z
Answers.Text: That's a clear way to explain loops. I use a similar approach.
Answers.UserDisplayName: Edwin Torres
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-15T21:58:46.353Z
Answers.Text: The do while and while loops stated aren't exactly equivalent. If after initialization, condition is false, then you never execute statement+update in the while loop, but in the do-while loop, you  always execute statement+update at least once. This could easily lead to confusion.
Answers.UserDisplayName: Batman
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-15T22:05:44.260Z
Answers.Text: @Batman Absolutely. That would be part of a broader instruction on the differences between and among these three loop constructs. Nevertheless, the general pseudocode holds true.
Answers.UserDisplayName: Peter
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-02-23T23:08:04.663Z
Answers.Text: My treatment of this differs only in that I call the third part "between' instead of update. This is the right approach.  Also, it's' good to draw a diagram depicting the loop and pointing out the cycle in the graph. Hence "loop."
Answers.UserDisplayName: ncmathsadist
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2017-07-14T04:59:28.217Z
Answers.LastActivityDate: 2020-10-06T03:18:19.900Z
Answers.LastEditDate: 2020-10-06T03:18:19.900Z
Answers.UserDisplayName: Peter
Answers.Body: <p>I used to have a role where I supported college students in CS1. I developed the following exercises to address this exact issue:</p>
  <hr />
  <h1>Counting code executions</h1>
  <p><a href="https://i.sstatic.net/dEQsbm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dEQsbm.png" alt="Peer Instruction exercise about for loops" /></a></p>
  <p><em>Text version:</em></p>
  <p>How many times do each of the following pieces of code execute?</p>
  <pre class="lang-c prettyprint-override"><code>int sum = 0;
  int i;
  for(i = 1 /*A*/; i &lt; 5 /*B*/; i = i + 1 /*C*/)
  {
      sum = sum + i; /*D*/
  }
  </code></pre>
  <p>Hint: translate a while loop -- the pieces should execute the same number of times as the do here.</p>
  <h1>Translating loops</h1>
  <p>Work on each of these individually first, then partner up. Switch partners between exercises.</p>
  <p>A. Convert this while loop into a for loop:</p>
  <pre class="lang-c prettyprint-override"><code>int k = 0;
  while (k &lt; 7) {
      cout &lt;&lt; &quot;Hola &quot; &lt;&lt; k &lt;&lt; endl;
      k = k + 2;
  }
  </code></pre>
  <p>What is the output of the loop?</p>
  <p>What is the value of <code>k</code> after the loop completes?</p>
  <p>Watch your peer leader be a human compiler on this loop.</p>
  <p>B. Convert this for loop into a while loop</p>
  <pre class="lang-c prettyprint-override"><code>for (int countdown = 10; countdown &gt;= 0; countdown--) {
      cout &lt;&lt; &quot;T-minus &quot; &lt;&lt; countdown &lt;&lt; endl;
  }
  cout &lt;&lt; &quot;BLASTOFF!!!&quot; &lt;&lt; endl;
  </code></pre>
  <p>What is the value of the countdown after the loop completes?</p>
  <hr />
  <p>If you teach very well maybe the questions are too easy, but in my setting they led to a lot of improvement. Notice that I included a counter increasing by something other than 1, and a loop counting downwards, since my students often didn't see examples like that in class.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-16T22:14:24.233Z
Answers.Text: Hyper-clarity *is* teaching well. This is an excellent exercise. Welcome to [cseducators.se]. I hope we hear more from you in the future!
Answers.UserDisplayName: Ben I.
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-16T22:53:18.007Z
Answers.Text: This isn't _just_ an answer; it also has useful material in it that'd be of general value to educators.  At current, SE.CSEducators doesn't really have a good mechanism for promoting this content, though there might be an argument for cloning StackOverflow's recent Documentation feature here - just, instead of being documentation on programming, it'd be a repository of teaching material.
Answers.UserDisplayName: Nat
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-16T22:59:36.487Z
Answers.Text: @Nat That actually sounds like a fantastic idea! If you want to, create a meta question requesting it. It's certainly unprecedented, but it's worth asking :)
Answers.UserDisplayName: thesecretmaster
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-16T23:00:43.923Z
Answers.Text: @Nat (and nova) I forgot to mention, come by the [chat room](https://chat.stackexchange.com/rooms/59174/the-classroom). We'd love to meet you!
Answers.UserDisplayName: Ben I.
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2017-07-16T22:12:01.673Z
Answers.LastActivityDate: 2020-10-06T03:17:43.100Z
Answers.LastEditDate: 2020-10-06T03:17:43.100Z
Answers.UserDisplayName: nova
Answers.Body: <p>I think the way to teach it is not by talking about order of operation, but by teaching the overall concept of a looping. The <code>for</code> header contains the steps that are generally common to looping: initialize iteration variables, test whether the loop should proceed, and update variables between iterations.</p>
  
  <p>As others have suggested, you could start by teaching <code>while</code> loops, since they have simpler structure. Then you could point out that many of these loops have some common structure: they initialize a variable before starting, and update that variable at the end of the body. This is so common that we have a special <code>for</code> statement that encapsulates it.</p>
  
  <p>This is also useful as an illustration of modularity, which is a cornerstone of good programming. Whenever you find yourself doing similar things over and over, give that thing a name and encode it as a function, macro, structure/class, etc. In this case, it's just happening at a higher level, in language design: much of the evolution of languages over the decades has been finding common programming patterns and creating languages that have them as built-in operations and/or functions (e.g. <code>foreach</code> in PHP).</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T21:20:17.140Z
Answers.LastActivityDate: 2017-07-14T21:20:17.140Z
Answers.UserDisplayName: Barmar
Answers.Body: <p>Maybe the</p>
  <pre class="lang-c prettyprint-override"><code>for (int i=0; i&lt;10; i++)
  { ... }
  </code></pre>
  <p>loops seems funny when you compare it to the &quot;interval&quot; loop of other languages, like Pascal's</p>
  <pre class="lang-pascal prettyprint-override"><code>for I:=1 to 10 by 1 do
  </code></pre>
  <p>but the C for loop was designed as a much more general linguistic mechanism than loops with counters.</p>
  <p>The objective was to keep all elements of the &quot;control&quot; of the loop together on one side for better maintenance, and the body of the loop on the other side.</p>
  <p>So we have a lot of additional common idioms, like</p>
  <pre class="lang-c prettyprint-override"><code>for (char *ptr = string; ptr != '\O'; ptr++) { ... }
  
  for (struct Cell *p = first; p != NULL;  p = p-&gt;next) { ... }
  </code></pre>
  <p>The loop over an interval is only an instance.  Maybe the problem is in the overuse of counters in the exercices for beginners (even when the range-based for loop is available). A survival from good old Fortran programming :-) ?</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2017-07-19T20:03:37.467Z
Answers.LastActivityDate: 2020-11-20T18:57:32.193Z
Answers.LastEditDate: 2020-11-20T18:57:32.193Z
Answers.UserDisplayName: Michel Billaud
Answers.Body: <p>I am not an educator, but I hope my answer will be helpful.</p>
  
  <p>In B.A.S.I.C, which I learned as a child, there are "for-to-step" loops and their argument order is the same as C style languages. I have to remember them like this in order to keep it right for myself.</p>
  
  <p>This is QBASIC</p>
  
  <pre><code>FOR counter = start TO end [STEP]
      [Statement Block] 
  NEXT counter
  </code></pre>
  
  <p>or</p>
  
  <pre><code>FOR i= 100 TO 0 STEP -1
      PRINT i 
  NEXT i
  </code></pre>
  
  <p>This helps me personaly understand what's happening in those loops.</p>
  
  <p>Another thing you might try is an alteration of what you posted above:</p>
  
  <pre><code> for (1; //initialize
        2; /* are we done? */ 4 /*increment*/){
        3 //do the work
   } // finish
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T14:09:32.880Z
Answers.LastActivityDate: 2017-07-15T17:17:48.200Z
Answers.LastEditDate: 2017-07-15T17:17:48.200Z
Answers.UserDisplayName: TecBrat
Answers.Body: <p>I love thesecretmaster's answer of showing the mapping between the two loops (and I will almost certainly do that in the future). However, as an AP Computer Science A teacher, I teach in Java, and there is a subtle trap in saying that</p>
  <pre class="lang-c prettyprint-override"><code>for (int i = 0; i &lt; 100; i++) {
      // do something
  }
  </code></pre>
  <p>is equal to</p>
  <pre class="lang-c prettyprint-override"><code>int i = 0;
  while (i &lt; 100) {
      // do something
      i++;
  }
  </code></pre>
  <p>The two loops are identical, but of course there is one subtle but important difference: the scope of <code>i</code> (and its corresponding pollution of the namespace).  Java considers the int declared in the first section of the for-loop header to be declared <em>in the loop</em>, and therefore out of scope once the loop ends.</p>
  <p>The <code>while</code> loop is really equivalent to this loop in C:</p>
  <pre class="lang-c prettyprint-override"><code>int i;
  for (i = 0; i &lt; 100; i++) {
      // do something
  }
  </code></pre>
  <p>If you are to take the path of mapping equivalencies between the loops, you really should also point out this trap.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T15:08:50.790Z
Answers.Text: You have a good point about the scope issue, though that's less a difference and more an issue of an incomplete translation.
    As noted in [@IllusiveBrian's comment](https://cseducators.stackexchange.com/questions/2632/teaching-the-humble-for-loop#comment4244_2634), `{}` need to be included to control for scope - which may look unusual since most people don't care enough about scope, but it's needed to maintain equivalence.
Answers.UserDisplayName: Nat
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T15:11:03.040Z
Answers.Text: For example, the `int i = 0; while (i< 100) { /* do something */ i++; }` above should be `{ int i = 0; while (i< 100) { /* do something */ i++; } }`.
Answers.UserDisplayName: Nat
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-19T20:14:56.190Z
Answers.Text: scope and pollution can be limited by a pair of curly brackets around declaration + loop.
Answers.UserDisplayName: Michel Billaud
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-02-10T16:59:54.967Z
Answers.Text: anyway, a `continue` statement in the body breaks the equivalence of the 2 pieces of code.
Answers.UserDisplayName: Michel Billaud
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-11-20T07:33:07.357Z
Answers.Text: @user737 when you're searching an array, a cleaner way (IMHO) is to use separate variables for iteration and result.
  `
  int index = -1 ; /* not found yet */
  for (int i = 0; i < size; i ++) {
       if (I found it) {
             result = i;
             break; 
  }}
  ` as it avoids leaking a temporary iteration variable outside the loop.
Answers.UserDisplayName: Michel Billaud
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2017-07-14T14:46:21.073Z
Answers.LastActivityDate: 2020-10-06T03:17:59.610Z
Answers.LastEditDate: 2020-10-06T03:17:59.610Z
Answers.UserDisplayName: Ben I.
Answers.Body: <p>However, don't neglect the fact that the first and last of the three sections between the parentheses can have (in C, anyway) multiple statements separated by commas (comma is an operator in C).</p>
  <pre class="lang-c prettyprint-override"><code>for(int i = 0, j = 100; i &lt; 100; i++, j = 2 * j + i) {
      //do something strange
  };
  </code></pre>
  <p>You can write quite a lot of a program in a single <code>for</code> statement. The final section needn't just increment or decrement things. Arbitrary complexity is possible. Probably not a good idea to encourage it, however. But students reading code of others may come across it, so should be aware.</p>
  <p>One use of this is to iterate over a two (or more) dimensional array in a single <code>for</code> statement.</p>
  <p>Because of the complexity, it is probably best to show how it maps to a while statement as suggested in another answer here</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-05-16T20:13:55.300Z
Answers.Text: The question explicitly asks about the scenario where the "for" loop is being taught to the students for the first time. It is quite clear that even the simplest version of the "for" loop causes enough confusion as it is. Having considered that, the approach of teaching all the potential use cases of the "for" loop would serve no other purpose than to confuse the students even more, rather than to solve the problem. Good education is about filtering the material in order to teach the simplest, yet the most powerful concepts within the student's current knowledge level. {continues}
Answers.UserDisplayName: NOT CSEducator
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-05-16T20:15:14.350Z
Answers.Text: Indiscriminately regurgitating all the loosely-related pieces of information regarding the "for" loop that you happen to know, and supplementing that with examples displaying absolutely atrocious coding practices, is just going to flood the students, quickly result in mental fatigue, and that is bad teaching. There is no need to confuse them by introducing the loosely-related concepts of comma operator, sequence points, and the deep details of expression evaluation in this stage. If they are struggling with the simple for loop, learning about comma operator & co. won't help with that.
Answers.UserDisplayName: NOT CSEducator
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-05-16T20:38:12.437Z
Answers.Text: Hmmm. Thank you for the "Indiscriminately regurgitating" slam. But I have to disagree for a lot of reasons. First, students will often need to read programs that they haven't written themselves and so will see such constructs in many algorithmic programs. Second. There are certainly simple cases in which the initialization is more than one statement. If they haven't seen the "comma" syntax, then they will probably put some of that outside the loop, breaking the principle that things that belong together should _be_ together, leading to the potential for future errors when programs evolve. more
Answers.UserDisplayName: Buffy
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-05-16T20:40:56.847Z
Answers.Text: Likewise, the update between iterations is a single statement in only the simplest of cases, and in anything more sophisticated, the student will be tempted to but that in the body of the loop (or part of it), possibly breaking abstraction as well as leading to future errors as well. If you teach them so little of C that they can only program awkwardly in what they have, you aren't doing them any favors.
Answers.UserDisplayName: Buffy
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T03:14:02.213Z
Answers.Text: Is the order of evaluation in your "step" even defined?
Answers.UserDisplayName: Džuris
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T05:06:13.967Z
Answers.Text: @Džuris yes. There is a sequence point between the evaluation of the left and right hand sides of the comma operator.
Answers.UserDisplayName: hobbs
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T05:08:49.587Z
Answers.Text: (but calling it "multiple statements" isn't accurate. It's a single expression. And the `int i = 0, int j = 100` part actually isn't valid because that's not how declarations work, though it would be without the second `int`).
Answers.UserDisplayName: hobbs
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-14T09:08:49.690Z
Answers.Text: @hobbs oops and Thanks. Corrected to remove the declaration from the loop.
Answers.UserDisplayName: Buffy
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2017-07-13T23:27:43.903Z
Answers.LastActivityDate: 2020-10-05T19:57:02.583Z
Answers.LastEditDate: 2020-10-05T19:57:02.583Z
Answers.UserDisplayName: Buffy
Answers.Body: <p>Another way of looking at this is to explore what is missing or lost at various stages:</p>
  <p>In Java</p>
  <p>For each:</p>
  <pre class="lang-java prettyprint-override"><code>for ( String s : &lt; some iteratable collection &gt; )
      foo();
  </code></pre>
  <p>loses the index of the loop. It never has one unless you add it.</p>
  <pre class="lang-java prettyprint-override"><code>for (int i = 0; i&lt; n; i++)
      foo();
  </code></pre>
  <p>loses the index after the loop when completed,</p>
  <p>while other loops preserve it.</p>
  <p>Many of the posts offer good advice for explaining the behaviour of the <code>for</code> loop.  Translations to and from <code>while</code> loops are traditionally used. Strictly speaking a <code>for</code> loop is never required, it's a convenience, as is the for each loop.</p>
  <p>The more tricky uses of a for loop should be very carefully considered before teaching -- high risk low reward.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-02-06T15:17:25.160Z
Answers.Text: I agree about de-stressing low reward features. However, they can't be neglected entirely as students (and professionals) still need to read the code of others who might not exhibit such "sanitary" practices.
Answers.UserDisplayName: Buffy
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-02-06T16:58:32.427Z
Answers.Text: I would add that it is also heavily tested on the AP CS A test, where they love to introduce off-by-one errors and tricky ending conditions.
Answers.UserDisplayName: Ben I.
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-02-06T15:09:53.517Z
Answers.LastActivityDate: 2020-10-06T03:16:43.000Z
Answers.LastEditDate: 2020-10-06T03:16:43.000Z
Answers.UserDisplayName: Mr Bradley
Body: <p>So, in C-style languages, the <code>for</code> loop has a funny little syntax:</p>
  <pre class="lang-c prettyprint-override"><code>for (int i = 0; i &lt; 100; i++) {
      // do something
  }
  </code></pre>
  <p>If we order these sections in a natural, intuitive fashion, we would get something like:</p>
  <pre><code>for (1; 2; 3) {
      4
  }
  </code></pre>
  <p>... which is how students seem to feel like things should be ordered.  But, of course, the real execution order is <code>1, 2, 4, 3, 2, 4, 3, 2, 4, 3, 2, 4, 3...</code></p>
  <p>What tricks have you developed for helping students make sense of <code>for</code> loops at the very start?</p>
  
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2018-02-23T23:16:29.260Z
Comments.Text: Teach them to learn what things mean instead of guessing from how they look.
Comments.UserDisplayName: philipxy
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-13T22:48:50.177Z
Comments.Text: In the C-style languages is it allowed to let step be a default? I.e., is `for (int i = 0; i < 100; ) {` legal and intrepreted as increment `i` by one each step?
Comments.UserDisplayName: Gypsy Spellweaver
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-13T23:15:16.013Z
Comments.Text: Actually that is legal, but is an infinite loop, with i always 1. Also: defaults of all kinds are frequent sources of error. Make your programs explicit.
Comments.UserDisplayName: Buffy
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-14T00:12:00.007Z
Comments.Text: I asked, because frequently parameters are often set up so that they can be dropped (defaulted) in reverse order (right-to-left). In the case of `for`, if that's part of the logic in creating the syntax, it can be given as `for (int i = 0; i < 100; ){`, or `for (int i = 0 ; ; ){`  but not `for (int i = 0 ; ; i++) {` because the center term is empty, while some term to the right is not empty.
Comments.UserDisplayName: Gypsy Spellweaver
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-14T05:01:37.400Z
Comments.Text: @GypsySpellweaver any or all of them can be empty, in any combination, but they all default to nothing (respectively: no initialization, no termination except by explicit `break`, and no post-loop-body expression).
Comments.UserDisplayName: hobbs
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-14T05:10:51.197Z
Comments.Text: @hobbs I was suspecting that they were independently "empty-legal" since they are, in essence commands (with the `;` separator), but the habit of what makes sense to the language creators for a parameter list probably had its influence. Having started with a different language, with explicit syntax would help the students. Something like `FOR int x = 1 TO 100 STEP 1` leaves no doubt, while being less adaptable.
Comments.UserDisplayName: Gypsy Spellweaver
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-14T13:43:33.463Z
Comments.Text: Can you add some specific problems your students seem to have with learning the for loop?
Comments.UserDisplayName: AnoE
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-14T18:58:11.047Z
Comments.Text: @GypsySpellweaver - No, there is no default behavior to a C-style for loop.  The three parts are valid C expressions that don't necessarily have anything to do with indexing a variable.  The expression could read another line of input from a file and the exit test could be checking for <EOF>.  It is very flexible and powerful, but you must tell it exactly what you want it to do.
Comments.UserDisplayName: MrWonderful
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-14T21:32:39.470Z
Comments.Text: I got a much deeper understanding of `for-loop`s when my teacher started leaving `1`, `2`, or `3` blank, switched the variables in `1`, `2`, and `3` from `ints` to `booleans` (or even `Strings` in Java), or made loops that required logic in `4` to make `2` true (and `3` was obsolete). I started to understand what each part meant and how to use it, instead of assuming `for-loop`s were always "increment an int until it hits a certain value".
Comments.UserDisplayName: Lord Farquaad
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-15T12:41:47.477Z
Comments.Text: A for loop in c style syntax is a shortcut for a while loop with post operation (increment being a common case).  Show the expanded while form, then show the for form.
Comments.UserDisplayName: pojo-guy
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-17T11:00:27.593Z
Comments.Text: This is why you shouldn't teach basic programming using C. It makes it extra hard to grasp the concept itself...
Comments.UserDisplayName: vacip
Tags: <best-practice><looping>
Title: Teaching the humble for loop
ThreadText: # Teaching the humble for loop
  
  (Asked by: username_0 on 2017-07-13)
  
  So, in C-style languages, the `for` loop has a funny little syntax:
  
  ```c
  for (int i = 0; i < 100; i++) {
      // do something
  }
  
  ```
  
  If we order these sections in a natural, intuitive fashion, we would get something like:
  
  ```
  for (1; 2; 3) {
      4
  }
  
  ```
  
  ... which is how students seem to feel like things should be ordered. But, of course, the real execution order is `1, 2, 4, 3, 2, 4, 3, 2, 4, 3, 2, 4, 3...`
  
  What tricks have you developed for helping students make sense of `for` loops at the very start?
  
  **Tags:** best-practice, looping
  
  > **Comments:**
  > **username_2**: In the C-style languages is it allowed to let step be a default? I.e., is `for (int i = 0; i < 100; ) {` legal and intrepreted as increment `i` by one each step?  
  > **username_3**: Actually that is legal, but is an infinite loop, with i always 1. Also: defaults of all kinds are frequent sources of error. Make your programs explicit.  
  > **username_2**: I asked, because frequently parameters are often set up so that they can be dropped (defaulted) in reverse order (right-to-left). In the case of `for`, if that's part of the logic in creating the syntax, it can be given as `for (int i = 0; i < 100; ){`, or `for (int i = 0 ; ; ){`  but not `for (int i = 0 ; ; i++) {` because the center term is empty, while some term to the right is not empty.  
  > **username_4**: @username_2 any or all of them can be empty, in any combination, but they all default to nothing (respectively: no initialization, no termination except by explicit `break`, and no post-loop-body expression).  
  > **username_2**: @username_4 I was suspecting that they were independently "empty-legal" since they are, in essence commands (with the `;` separator), but the habit of what makes sense to the language creators for a parameter list probably had its influence. Having started with a different language, with explicit syntax would help the students. Something like `FOR int x = 1 TO 100 STEP 1` leaves no doubt, while being less adaptable.  
  > **username_5**: Can you add some specific problems your students seem to have with learning the for loop?  
  > **username_6**: @username_2 - No, there is no default behavior to a C-style for loop.  The three parts are valid C expressions that don't necessarily have anything to do with indexing a variable.  The expression could read another line of input from a file and the exit test could be checking for <EOF>.  It is very flexible and powerful, but you must tell it exactly what you want it to do.  
  > **username_7**: I got a much deeper understanding of `for-loop`s when my teacher started leaving `1`, `2`, or `3` blank, switched the variables in `1`, `2`, and `3` from `ints` to `booleans` (or even `Strings` in Java), or made loops that required logic in `4` to make `2` true (and `3` was obsolete). I started to understand what each part meant and how to use it, instead of assuming `for-loop`s were always "increment an int until it hits a certain value".  
  > **username_8**: A for loop in c style syntax is a shortcut for a while loop with post operation (increment being a common case).  Show the expanded while form, then show the for form.  
  > **username_9**: This is why you shouldn't teach basic programming using C. It makes it extra hard to grasp the concept itself...  
  > **username_1**: Teach them to learn what things mean instead of guessing from how they look.  
  
  ---
  
  ## 14 answers
  
  ### Answer by username_21 on 2018-02-07. Score: 34 | Accepted answer
  
  I know I'm coming late to this party but this is a really good question and I think it deserves a really good treatment.
  
  The original `for` loop, the one with the semicolons in it, is amazingly flexible, powerful, and confusing as all get out. It is seldom taught well, it is a very easy place for bugs to hide, and it is not going away.
  
  To master it you must learn the 1,   2, 4, 3,   2, 4, 3 pattern the OP mentioned. You must burn it into your soul. You must burn it into the souls of your students. The question is, how?
  
  The best way is to actually see it. To watch it happen. Unfortunately debugging tools often insist on highlighting the entire line.
  
  [![debugger highlighting the full line](https://i.sstatic.net/4tVJT.png)](https://i.sstatic.net/4tVJT.png)
  
  Can you tell if `i` is about to be initialized, tested, or incremented here? Debugger highlighting is often useless for teaching or debugging the classic for loop.
  
  However, there is a way around that problem. The c style languages all have a feature that lets us work around this debugger limitation. Whitespace. Whitespace is meaningless in these languages. You can take advantage of that.
  
  So long as you're willing to explain that this:
  
  ```java
  for(int i=0; i<10; i++) {
      System.out.println(i);
  }
  
  ```
  
  will do the same thing as this:
  
  ```java
  for(
          int i=0; 
          i<10; 
          i++
  ) {
      System.out.println(i);
  }
  
  ```
  
  then you can show them this:
  
  [![debugger single-stepping for-loop parts](https://i.sstatic.net/2K5ny.gif)](https://i.sstatic.net/2K5ny.gif)
  
  Do that, and rather than just explaining, you are showing them how this works, you are teaching them how to debug it themselves when they get confused by it.
  
  Now sure [the multiline style](//softwareengineering.stackexchange.com/a/331680/131624) isn't popular with for loops but the students certainly don't have to turn in code that looks like that. It's just a form to use while testing because our debugging tools aren't yet smart enough to highlight only the relevant parts of a line.
  
  I've changed the speed and rhythm I use as I click. That's no accident. I'm using that to emphasize the starting and ending parts of each iteration. Students should not only feel like they can predict this. They should feel like they can use the debugger to re-teach themselves this pattern quickly if they ever need to.
  
  Consider a cascading style that retains column position for those more visually oriented:
  
  [![same as last, but for-loop parts stay in the column they would have if it was a single line](https://i.sstatic.net/UB41P.gif)](https://i.sstatic.net/UB41P.gif)
  
  Now that's just the start of understanding loops. Writing [correct, readable, efficient loops](//softwareengineering.stackexchange.com/q/315964/131624) is a whole other issue that this answer hardly does justice to.
  
  A lot of bugs hide right here. Don't undersell how worthy this is of close study.
  
  > **Comments:**
  > **username_3**: You may be late to our "party" and I haven't noticed you here before, but you are giving some great answers. I'd offer you a party hat if I had one. Oh, I do, +1.  
  > **username_21**: @username_3 hehe, thank you. This isn't my usual haunt but I can't resist a good question.  
  > **username_22**: This just might be the most useful answer I've seen in the last 3 months.  
  > **username_23**: A nice solution and in the "video" you made it even better than in the "code", as I think the "video" has a better indentation.  
  > **username_21**: @username_23 thank you. I realized the advantage of that form late and wanted to tack it on. After decades at this I'm still learning new tricks : )  
  > **username_24**: Wow--what a great suggestion for demonstrating a for loop.  
  > **username_25**: This is a nifty idea, but some IDEs can't highlight the distinct parts of the for-loop, even when split into separate lines in the source file. For example, I tried this in the Dev-C++ debugger and it only highlights the initializer part on any interation.  
  > **username_21**: @username_25 consider filing a bug. Feel free to link them to this answer to demonstrate the desired behavior. Wish all debuggers highlighted for loops correctly, regardless of line breaks.  
  > **username_25**: @username_21: This open-source IDE doesn't have support like that.  
  > **username_21**: @username_25 consider using an IDE that has support. Or, since it’s open source, supporting it yourself.  
  > **username_26**: What we really need is debuggers to learn that a single line of code can contain several independent items (statements).  
  
  ---
  
  ### Answer by username_11 on 2017-07-13. Score: 59
  
  Show then how the loop can be unfolded into a while loop:
  
  ```c
  int i = 0 // Step 1
  while (i< 100) { // Step 2
      // Do something
      i++ // Step 3
  }
  
  ```
  
  Explain that the order is derived from that unfolding.
  
  You could start out by only teaching while loops, forcing them to make these while loops with iterators, then showing that for loops are a condensed of those while loops with incrementing variables.
  
  > **Comments:**
  > **username_12**: …and be prepared for the question "*Why should we use `for` loops instead of `while` loops when they're doing equivalent things, what's their **advantage**?*"  
  > **username_11**: @username_12 You're telling the compiler what you want more clearly, allowing more optimization, and they simply take up less space and look neater.  
  > **username_12**: @username_11 "Required to tell the compiler…" has never been a good reason. And I can only hope that the syntax choice does not affect the optimiser at all. The point is that they are easier to understand *for the programmer(s)* that have to read them. The iteration variable is (supposed to be) initialised and modified only in that single line, which makes for a an easily recognisable pattern and correct code where the update step is not forgotten. It also works with `continue;`  
  > **username_13**: @username_12 Keeping the loop control variable in the `for` scope is a practical advantage as well.  The more correct "expansion" of a `for` loop would be: `{int i = 0; while(i < 100){++i;}}`.  
  > **username_14**: @username_13 creation of the loop variable inside the `for(` statement wasn't possible until C99 allowed it.  
  > **username_15**: For loops do not optimise better than while loops (at least in gcc, clang and visual studio in C and C++). Arguments about easier to read code are sensible.  
  > **username_16**: Won't this lead to teaching the Duff's device? That's not a path I'd recommend with students this fresh.  
  > **username_17**: I would like to add that, even though the while and for loops may be the same, in practical terms I would favor new programmers using the for loop, as it makes it much less likely to accidentally produce an infinite loop.  
  > **username_18**: About the cliché "for loop are syntactical sugar around while", it must be noted that the C for-loop was present already present in  B https://www.thinkage.ca/english/gcos/expl/b/manu/manu.html#Section5_7_4 together with a `forever` loop which is leaved by break or goto. So the while loop is a shortcut for   `forever {  if (! condition) break; .... }` if you are sugar addicted.  
  > **username_18**: And, actually, `while(cond) instr` is syntactic sugar around the special case `for(;cond;) instr;` as it preserves the meaning of a `continue` statement, not the other way. The fact is, our opinions about which is more fundamental may be biased when we prevously taught Pascal where there is no equivalent to the C-like for loop.  
  > **username_19**: @username_12: "When you've dealt with iterative code for years, no matter which iteration is used, you [no longer see all of the code](https://78.media.tumblr.com/f8b9a8f9209c1220b0876a9ead23f353/tumblr_oylvu4FbMc1weu5xbo1_500.gif), you're only going to be looking at the important bits: initialization, evalutation to loop again, and how to change the evaluation with every loop that  is executed. The `while` syntax separates these bits and keeps them far away (unless the `while` body is trivially small, which it won't be in the real world), but the `for` keeps those things together, visually."  
  > **username_20**: There is a difference in this while loop: the loop variable has scope beyond the end of the loop.  
  
  ---
  
  ### Answer by username_30 on 2017-07-14. Score: 26
  
  I teach `for` loops using the following pseudocode, which we then translate into actual code:
  
  ```c
  for (initialization; condition; update)
  {
      statement;
  }
  
  ```
  
  This logic helps justify why the order goes `1, 2, 4, 3` to start. I explain it as follows: a variable can only be initialized once so it happens first and never again. After that the variable is tested against the condition. If the condition is true, then the code proceeds to the statement. Only then will it reach update. If the first conditional test fails, the update code is never executed.
  
  I have found that `for` loops are one of the few constructs that benefit most directly from drawing a flowchart. Using the visual diagram will help this logic become clearer.
  
  Another benefit of teaching the `for` loop this way is that it becomes trivial to translate it into `while` or `do-while` with the same pseudocode constructs.
  
  ```c
  // while loop
  initialization;
  while (condition)
  {
      statement;
      update;
  }
  
  // do-while loop
  initialization;
  do
  {
      statement;
      update;
  } while (condition);
  
  ```
  
  Once I do this, I can focus on each of these four parts, so students understand the different components that make up a loop regardless of the structure thereof.
  
  > **Comments:**
  > **username_31**: That's a clear way to explain loops. I use a similar approach.  
  > **username_32**: The do while and while loops stated aren't exactly equivalent. If after initialization, condition is false, then you never execute statement+update in the while loop, but in the do-while loop, you  always execute statement+update at least once. This could easily lead to confusion.  
  > **username_30**: @username_32 Absolutely. That would be part of a broader instruction on the differences between and among these three loop constructs. Nevertheless, the general pseudocode holds true.  
  > **username_20**: My treatment of this differs only in that I call the third part "between' instead of update. This is the right approach.  Also, it's' good to draw a diagram depicting the loop and pointing out the cycle in the graph. Hence "loop."  
  
  ---
  
  ### Answer by username_27 on 2017-07-14. Score: 9
  
  Theoretically, I teach the while loop first. Others have already explained how and why, but I'll go ahead with an example:
  
  ```c
  void showRating( int rating )
  {
      int i = 0;
      while ( i < rating )
      {
          putchar( '*' );
          ++i;
      }
      putchar( '\n' );
  }
  
  ```
  
  Some of the examples will be better expressed as for loops, and that's where I introduce the for loop, as a way of containing the essential elements in a concise construct. I might ask what happens if I forget to increment *i*:
  
  ```c
  void showRating( int rating )
  {
      int i = 0;
      while ( i < rating )
      {
          putchar( '*' );
      }
      putchar( '\n' );
  }
  
  ```
  
  And we compile it and run it.
  
  Then I show how the for loop might help us not forget the counter:
  
  ```c
  void showRating( int rating )
  {
      int i;
      for ( i = 0; i < rating; ++i )
      {
          putchar( '*' );
      }
      putchar( '\n' );
  }
  
  ```
  
  Too often, people think first of counting when they think of loops, and that's why they jump to the for loop first. But the C for loop is not really the counted loop that BASIC has led us to believe it is. And the English grammar for the word is not limited to counting, either.
  
  So I'll throw some for loops in that don't strictly count.
  
  I also teach the pun on forever that used to be the standard flag for an indeterminate loop:
  
  ```c
  for( ;; )
  
  ```
  
  I'm likely to teach the post-test do ... while loop after having shown an indeterminate loop with a break at the end:
  
  ```c
  for ( ;; )
  {
      /* Always executes once. */
      if ( condition ) break;
  }
  
  ```
  
  Now I would want to use something concrete here so I can show that it really always executes once, but I don't have time to make something up today.
  
  Then I can show them the do .. while loop:
  
  ```c
  do
  {
      /* Always executes once. */
  } while ( !condition );
  
  ```
  
  Somewhere along in here I'll introduce the faux style thing about bracket placement and warn them not to argue with the managers about where to place them.
  
  
  ---
  
  ### Answer by username_28 on 2017-07-13. Score: 9
  
  It's about setting boundary conditions first. Provide them with a more concrete example, like filling a glass of milk. You kind of need a glass or container (let me know the next time you pour milk right on the counter) and that glass is some amount full. We'll just treat it as empty. Then, you stop filling the glass when it's full (or half full or whatever), unless you want milk everywhere.
  
  Within those boundary conditions, you pour the milk jug. That is, mentally, you're thinking (in not so many terms):
  
  ```
  repeat following until checks make you stop pouring milk
  check: fullness of glass
  check: how close the fullness is to the wanted end fullness
  add some milk
  
  ```
  
  That's exactly how a for loop thinks. It needs your conditions *first*, and then what you want to repeat while those conditions are true. (Yes, *while* - just like a while loop. I personally agree with username_11 in that it makes a lot of sense to introduce while loops before for loops.) As you're pouring, you're constantly rechecking the level of the milk - "updating" a variable in your head as you act. So, if you were asking a computer to fill a glass of milk:
  
  ```c
  import milk
  for (float glassFullness = 0; glassFullness < 1; glassFullness+=0.1) {
      milk.Fill()
  }
  
  ```
  
  That could, of course, also be written
  
  ```c
  import milk
  float glassFullness = 0;
  while (glassFullness < 1) {
      milk.Fill()
      glassFullness+=0.1
  }
  
  ```
  
  They're doing the same things; the for loop is just a condensed version.
  
  **Tl;dr: a for loop looks for the boundary conditions, and then does what it needs to do, rechecking with a redefined variable accounting for the change that has been made. You input what change needs to be made to the variable to account for the action.**
  
  
  ---
  
  ### Answer by username_29 on 2017-07-14. Score: 9
  
  ***tl;dr*–** A `for` loop is just a `while` loop that has extra slots for a pre-loop statement and a post-loop-run statement. Since they're pretty much the same thing just written differently, a `for` loop is best understood as [syntactic sugar](https://en.wikipedia.org/wiki/Syntactic_sugar) that's useful when it increases the readability of the code.
  
  Sometimes new programmers are worried about performance, thinking that syntactic sugar might be less efficient. That's not the case; the compiler really doesn't care how you write these loops, it's all the same to it. So, students should be told to just write whichever's cleaner in the current context.
  
  **Homework/test question idea:** Have students convert a `for` loop into an equivalent `while` loop, or a `while` loop into an equivalent `for` loop.
  
  ---
  
  ### Mapping between `for` and `while`.
  
  The `for` loop:
  
  ```c
  for (prestatement; condition; poststatement)
  {
      // loop body
  }
  
  ```
  
  is equivalent to the `while` loop:
  
  ```c
  {
      prestatement;
      while (condition)
      {
          // loop body
          poststatement;
      }
  }
  
  ```
  
  , where:
  
  * `prestatement` is an executable statement that happens only once, before the loop starts.
  
    + If omitted, then the loop just doesn't do anything extra before starting.
  * `condition` is a `Boolean` expression that's evaluated at the start of each loop execution, breaking if `false`.
  
    + If omitted, then there's no break check there.
  * `poststatement` is an executable statement that happens after the end of each loop execution.
  
    + If omitted, then the loop just doesn't do anything extra after each execution.
  
  ---
  
  ### Note on scope.
  
  Even though
  
  ```c
      int i = 0;
      int i = 0;
  
  ```
  
  is illegal code because we can't declare `i` twice in the same scope,
  
  ```c
  {
      int i = 0;
  }
  {
      int i = 0;
  }
  
  ```
  
  is legal because both `i`'s are in different scopes.
  
  This scoping issue is why we have the `while` statement above wrapped in extra `{}`'s, since the `prestatement` belongs in that scope.
  
  ---
  
  ### Note on `continue`.
  
  The keyword `continue` can `goto` the end of a loop's body.
  
  We can rewrite this behavior more explicitly:
  
  1. Make the implicit-label explicit by writing it out.
  2. Rewrite `continue;` as `goto [label's name];`.
  
  For example:
  
  ```c
  for (long i=0; i < 1000; ++i)
  {
      if (i % 8 == 0) { continue; }
      //  rest of body
  }
  
  ```
  
  becomes
  
  ```c
  for (long i=0; i < 1000; ++i)
  {
      if (i % 8 == 0) { goto end_of_body; }
      //  rest of body
  end_of_body:
  }
  
  ```
  
  If we then rewrite this as a `while` loop, it'd be
  
  ```c
  {
      long i = 0;
      while (i < 1000)
      {
          if (i % 8 == 0) { goto end_of_body; }
          //  rest of body
  end_of_body:
          ++i;
      }
  }
  
  ```
  
  That said, generally `goto` and related mechanisms (e.g., `continue`) are discouraged. Presumably students ought to understand how they work, though it's generally best to avoid new usage.
  
  ---
  
  ### `for` loops can omit parts.
  
  Might seem weird at first glance, but
  
  ```c
  for (;;) { }
  
  ```
  
  is actually perfectly legal code! Since it omits a `break` condition and doesn't do anything, it's basically an infinite loop that runs forever without doing anything.
  
  In C#, it doesn't consume CPU time, but it also blocks the thread from progressing. For example,
  
  ```c
  for (;;) { }    //  Infinite loop
  foo();          //  Never happens because the above loop never ends
  
  ```
  
  > **Comments:**
  > **username_18**: Not only syntactical sugar around a `while` loop, as the `continue` statement of the `while` loop skips the "poststatement".  
  > **username_29**: @username_18: Good point, I should clarify the issue with `continue`.  Don't get me wrong, it's still just syntactic sugar, but probably ought to clarify that `continue` targets the spot after `//  loop body` in the translation.  
  > **username_18**: In C, control structures are mostly macros trying to hide some gotos under the carpet. But don't tell that to students.  
  
  ---
  
  ### Answer by username_33 on 2017-07-16. Score: 7
  
  I used to have a role where I supported college students in CS1. I developed the following exercises to address this exact issue:
  
  ---
  
  # Counting code executions
  
  [![Peer Instruction exercise about for loops](https://i.sstatic.net/dEQsbm.png)](https://i.sstatic.net/dEQsbm.png)
  
  *Text version:*
  
  How many times do each of the following pieces of code execute?
  
  ```c
  int sum = 0;
  int i;
  for(i = 1 /*A*/; i < 5 /*B*/; i = i + 1 /*C*/)
  {
      sum = sum + i; /*D*/
  }
  
  ```
  
  Hint: translate a while loop -- the pieces should execute the same number of times as the do here.
  
  # Translating loops
  
  Work on each of these individually first, then partner up. Switch partners between exercises.
  
  A. Convert this while loop into a for loop:
  
  ```c
  int k = 0;
  while (k < 7) {
      cout << "Hola " << k << endl;
      k = k + 2;
  }
  
  ```
  
  What is the output of the loop?
  
  What is the value of `k` after the loop completes?
  
  Watch your peer leader be a human compiler on this loop.
  
  B. Convert this for loop into a while loop
  
  ```c
  for (int countdown = 10; countdown >= 0; countdown--) {
      cout << "T-minus " << countdown << endl;
  }
  cout << "BLASTOFF!!!" << endl;
  
  ```
  
  What is the value of the countdown after the loop completes?
  
  ---
  
  If you teach very well maybe the questions are too easy, but in my setting they led to a lot of improvement. Notice that I included a counter increasing by something other than 1, and a loop counting downwards, since my students often didn't see examples like that in class.
  
  > **Comments:**
  > **username_0**: Hyper-clarity *is* teaching well. This is an excellent exercise. Welcome to [cseducators.se]. I hope we hear more from you in the future!  
  > **username_29**: This isn't _just_ an answer; it also has useful material in it that'd be of general value to educators.  At current, SE.CSEducators doesn't really have a good mechanism for promoting this content, though there might be an argument for cloning StackOverflow's recent Documentation feature here - just, instead of being documentation on programming, it'd be a repository of teaching material.  
  > **username_11**: @username_29 That actually sounds like a fantastic idea! If you want to, create a meta question requesting it. It's certainly unprecedented, but it's worth asking :)  
  > **username_0**: @username_29 (and username_33) I forgot to mention, come by the [chat room](https://chat.stackexchange.com/rooms/59174/the-classroom). We'd love to meet you!  
  
  ---
  
  ### Answer by username_34 on 2017-07-14. Score: 7
  
  I think the way to teach it is not by talking about order of operation, but by teaching the overall concept of a looping. The `for` header contains the steps that are generally common to looping: initialize iteration variables, test whether the loop should proceed, and update variables between iterations.
  
  As others have suggested, you could start by teaching `while` loops, since they have simpler structure. Then you could point out that many of these loops have some common structure: they initialize a variable before starting, and update that variable at the end of the body. This is so common that we have a special `for` statement that encapsulates it.
  
  This is also useful as an illustration of modularity, which is a cornerstone of good programming. Whenever you find yourself doing similar things over and over, give that thing a name and encode it as a function, macro, structure/class, etc. In this case, it's just happening at a higher level, in language design: much of the evolution of languages over the decades has been finding common programming patterns and creating languages that have them as built-in operations and/or functions (e.g. `foreach` in PHP).
  
  
  ---
  
  ### Answer by username_18 on 2017-07-19. Score: 5
  
  Maybe the
  
  ```c
  for (int i=0; i<10; i++)
  { ... }
  
  ```
  
  loops seems funny when you compare it to the "interval" loop of other languages, like Pascal's
  
  ```pascal
  for I:=1 to 10 by 1 do
  
  ```
  
  but the C for loop was designed as a much more general linguistic mechanism than loops with counters.
  
  The objective was to keep all elements of the "control" of the loop together on one side for better maintenance, and the body of the loop on the other side.
  
  So we have a lot of additional common idioms, like
  
  ```c
  for (char *ptr = string; ptr != '\O'; ptr++) { ... }
  
  for (struct Cell *p = first; p != NULL;  p = p->next) { ... }
  
  ```
  
  The loop over an interval is only an instance. Maybe the problem is in the overuse of counters in the exercices for beginners (even when the range-based for loop is available). A survival from good old Fortran programming :-) ?
  
  
  ---
  
  ### Answer by username_35 on 2017-07-14. Score: 4
  
  I am not an educator, but I hope my answer will be helpful.
  
  In B.A.S.I.C, which I learned as a child, there are "for-to-step" loops and their argument order is the same as C style languages. I have to remember them like this in order to keep it right for myself.
  
  This is QBASIC
  
  ```
  FOR counter = start TO end [STEP]
      [Statement Block] 
  NEXT counter
  
  ```
  
  or
  
  ```
  FOR i= 100 TO 0 STEP -1
      PRINT i 
  NEXT i
  
  ```
  
  This helps me personaly understand what's happening in those loops.
  
  Another thing you might try is an alteration of what you posted above:
  
  ```
   for (1; //initialize
        2; /* are we done? */ 4 /*increment*/){
        3 //do the work
   } // finish
  
  ```
  
  
  ---
  
  ### Answer by username_0 on 2017-07-14. Score: 3
  
  I love username_11's answer of showing the mapping between the two loops (and I will almost certainly do that in the future). However, as an AP Computer Science A teacher, I teach in Java, and there is a subtle trap in saying that
  
  ```c
  for (int i = 0; i < 100; i++) {
      // do something
  }
  
  ```
  
  is equal to
  
  ```c
  int i = 0;
  while (i < 100) {
      // do something
      i++;
  }
  
  ```
  
  The two loops are identical, but of course there is one subtle but important difference: the scope of `i` (and its corresponding pollution of the namespace). Java considers the int declared in the first section of the for-loop header to be declared *in the loop*, and therefore out of scope once the loop ends.
  
  The `while` loop is really equivalent to this loop in C:
  
  ```c
  int i;
  for (i = 0; i < 100; i++) {
      // do something
  }
  
  ```
  
  If you are to take the path of mapping equivalencies between the loops, you really should also point out this trap.
  
  > **Comments:**
  > **username_29**: You have a good point about the scope issue, though that's less a difference and more an issue of an incomplete translation.   As noted in [@username_13's comment](https://cseducators.stackexchange.com/questions/2632/teaching-the-humble-for-loop#comment4244_2634), `{}` need to be included to control for scope - which may look unusual since most people don't care enough about scope, but it's needed to maintain equivalence.  
  > **username_29**: For example, the `int i = 0; while (i< 100) { /* do something */ i++; }` above should be `{ int i = 0; while (i< 100) { /* do something */ i++; } }`.  
  > **username_18**: scope and pollution can be limited by a pair of curly brackets around declaration + loop.  
  > **username_18**: anyway, a `continue` statement in the body breaks the equivalence of the 2 pieces of code.  
  > **username_18**: @user737 when you're searching an array, a cleaner way (IMHO) is to use separate variables for iteration and result. ` int index = -1 ; /* not found yet */ for (int i = 0; i < size; i ++) {      if (I found it) {            result = i;            break;  }} ` as it avoids leaking a temporary iteration variable outside the loop.  
  
  ---
  
  ### Answer by username_3 on 2017-07-13. Score: 3
  
  However, don't neglect the fact that the first and last of the three sections between the parentheses can have (in C, anyway) multiple statements separated by commas (comma is an operator in C).
  
  ```c
  for(int i = 0, j = 100; i < 100; i++, j = 2 * j + i) {
      //do something strange
  };
  
  ```
  
  You can write quite a lot of a program in a single `for` statement. The final section needn't just increment or decrement things. Arbitrary complexity is possible. Probably not a good idea to encourage it, however. But students reading code of others may come across it, so should be aware.
  
  One use of this is to iterate over a two (or more) dimensional array in a single `for` statement.
  
  Because of the complexity, it is probably best to show how it maps to a while statement as suggested in another answer here
  
  > **Comments:**
  > **username_37**: Is the order of evaluation in your "step" even defined?  
  > **username_4**: @username_37 yes. There is a sequence point between the evaluation of the left and right hand sides of the comma operator.  
  > **username_4**: (but calling it "multiple statements" isn't accurate. It's a single expression. And the `int i = 0, int j = 100` part actually isn't valid because that's not how declarations work, though it would be without the second `int`).  
  > **username_3**: @username_4 oops and Thanks. Corrected to remove the declaration from the loop.  
  > **username_36**: The question explicitly asks about the scenario where the "for" loop is being taught to the students for the first time. It is quite clear that even the simplest version of the "for" loop causes enough confusion as it is. Having considered that, the approach of teaching all the potential use cases of the "for" loop would serve no other purpose than to confuse the students even more, rather than to solve the problem. Good education is about filtering the material in order to teach the simplest, yet the most powerful concepts within the student's current knowledge level. {continues}  
  > **username_36**: Indiscriminately regurgitating all the loosely-related pieces of information regarding the "for" loop that you happen to know, and supplementing that with examples displaying absolutely atrocious coding practices, is just going to flood the students, quickly result in mental fatigue, and that is bad teaching. There is no need to confuse them by introducing the loosely-related concepts of comma operator, sequence points, and the deep details of expression evaluation in this stage. If they are struggling with the simple for loop, learning about comma operator & co. won't help with that.  
  > **username_3**: Hmmm. Thank you for the "Indiscriminately regurgitating" slam. But I have to disagree for a lot of reasons. First, students will often need to read programs that they haven't written themselves and so will see such constructs in many algorithmic programs. Second. There are certainly simple cases in which the initialization is more than one statement. If they haven't seen the "comma" syntax, then they will probably put some of that outside the loop, breaking the principle that things that belong together should _be_ together, leading to the potential for future errors when programs evolve. more  
  > **username_3**: Likewise, the update between iterations is a single statement in only the simplest of cases, and in anything more sophisticated, the student will be tempted to but that in the body of the loop (or part of it), possibly breaking abstraction as well as leading to future errors as well. If you teach them so little of C that they can only program awkwardly in what they have, you aren't doing them any favors.  
  
  ---
  
  ### Answer by username_38 on 2018-02-06. Score: 3
  
  Another way of looking at this is to explore what is missing or lost at various stages:
  
  In Java
  
  For each:
  
  ```java
  for ( String s : < some iteratable collection > )
      foo();
  
  ```
  
  loses the index of the loop. It never has one unless you add it.
  
  ```java
  for (int i = 0; i< n; i++)
      foo();
  
  ```
  
  loses the index after the loop when completed,
  
  while other loops preserve it.
  
  Many of the posts offer good advice for explaining the behaviour of the `for` loop. Translations to and from `while` loops are traditionally used. Strictly speaking a `for` loop is never required, it's a convenience, as is the for each loop.
  
  The more tricky uses of a for loop should be very carefully considered before teaching -- high risk low reward.
  
  > **Comments:**
  > **username_3**: I agree about de-stressing low reward features. However, they can't be neglected entirely as students (and professionals) still need to read the code of others who might not exhibit such "sanitary" practices.  
  > **username_0**: I would add that it is also heavily tested on the AP CS A test, where they love to introduce off-by-one errors and tricky ending conditions.  
  
  ---
  
  ### Answer by username_10 on 2022-05-11. Score: 0
  
  I know I am very late to this party (and this idiom), but..
  
  The trick to teaching loops is pink hippos.
  
  There are five basic parts to a loop.
  
  1. Control Init (initialize the control variable)
  2. Loop Back Spot (a stupid name for the place the code jumps back to)
  3. Work (what you are repeating in the loop)
  4. Control Step (changing the loop control variable)
  5. Exit Check (checking the exit condition and jumping back as needed)
  
  Take a for loop (java for example)
  
  ```
    for (int ii = 2; ii < 20; ii = ii + 2)
       System.out.println(ii);
  
  ```
  
  with the parts labeled:
  
  ```
    <loop back spot> for (<control init>; <exit check>; <control step>) 
                          <work>
  
  ```
  
  To demonstrate this in class I take out of large jar with 30 little pink hippos and write the five parts left to right across the board. I then have five students come up to the front of the class room and stand under each of the loop parts. The one under the control step gets the jar of hippos.
  
  I then have a sixth student join the group at the front as the computer to run the code. The computer student receives one hippo at the start from the first student. That students job is done. The computer student then moves right passing the loop spot to the student at work. The student standing there then rights number of hippos the computer student is holding on the board. The exit check student then evaluates the total hippos and gets to declare if the computer student is done. Not enough hippos! Go back to the loop back spot. Continue with the computer student having to hang onto an increasingly hilarious number of hippos. As this is taking place I'm pointing out the order that things happen, and important details like you will never have a value outside the range while inside the for loop.
  
  The important points are made, and the students have a clear visual to hang the somewhat esoteric idea onto.
  
  > **Comments:**
  > **username_0**: Your loop back spot appears before the `for` declaration.  Why?  
  > **username_10**: The loop back spot is the for declaration.  Hard to show using text. When I'm explaining this in class I simply write a 2 and draw an arrow pointing at for.  
  
  ---
  
  