Answers.Body: <p>As a maybe overly simplistic example: Say you want to make mashed potatoes.  To make it easier we'll focus on one part of the process: prepping 5 potatoes.</p>
  <p>First, you would peel one, cut it up, and place it in a pot to be boiled.  Then, you would go through the same process with the second potato and continue with each potato until you are done.</p>
  <p>Ex:</p>
  <pre><code>For Each Potato {
      peel the potato
      slice the potato
      place it in a pot
  }
  </code></pre>
  <p>OR</p>
  <pre><code>for potato starting at 1 and ending at 5 {
      peeled_potato = peel(potato);
      sliced_potato = slice(peeled_potato);
      place_in_pot = into_pot(sliced_potato);
  }
  </code></pre>
  <p>Depending on your student, this may not fit culturally; however, I would argue a similarly structured recipe could be found in most cultures.  And yes, I'm assuming the student understands the basic idea of a recipe.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T13:51:40.887Z
Answers.Text: I would surely do this as at least two and probably 3 separate loops--peel all potatoes, then slice all potatoes, then put them all in the pot. Especially if you're peeling with a peeler and not a paring knife.
Answers.UserDisplayName: user3067860
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-11T17:27:03.350Z
Answers.Text: That would be another way to do it.  Personally, I would do it as described to prevent the potatoes oxidizing and turning brown while I am cutting them up.  Of course, I omitted the assumption there is water in the pot to further prevent oxidization. Reference:  [link](https://www.southernliving.com/food/veggies/potatoes/how-to-keep-potatoes-from-turning-brown#:~:text=Once%20they%20have%20been%20peeled,is%20completely%20safe%20to%20eat.)
Answers.UserDisplayName: Rakicy
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-12T15:38:59.000Z
Answers.Text: You can put them in water between the peeling and chopping steps to prevent browning, it will still be faster if the number of potatoes is large--I think it's interesting from a CS perspective because it goes to show that the faster answer depends on what the actual loops are doing, how many iterations there are, etc. The parts of the job that machine learning can't replace yet.
Answers.UserDisplayName: user3067860
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T16:07:28.903Z
Answers.LastActivityDate: 2023-05-29T16:07:28.903Z
Answers.UserDisplayName: Rakicy
Answers.Body: <p>The conventional <code>for</code> loop (in the c-like languages, at least) is a low-level iteration structure, and there are two challenges.  The first is to understand the mechanics of the thing, and the second is to grok its purpose.</p>
  <p>You are only asking about the latter, but I would caution not to dismiss the simple examples - they are the best tools for the former.  Without those mechanics, there is no fluency in the mind of the budding coder, and without that fluidity, they have an uphill battle to use the idea to build later ideas.</p>
  <p>That said, for loops are great for going through an array or a string, or for iterating up to a certain predetermined point.</p>
  <p>There comes a time when you will point out that <code>for</code> loops and <code>while</code> loops are equally powerful, but have to nevertheless explain that we use the former when we want to keep all of the iteration information together at the top, which is typically when the loop is simple, incremental, and stops at a known point.  For all other, more complicated situations, we tend towards <code>while</code> loops instead.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T10:28:59.790Z
Answers.Text: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/146334/discussion-on-answer-by-ben-i-what-is-a-real-world-example-of-a-for-loop); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
Answers.UserDisplayName: Ben I.
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-28T02:43:01.707Z
Answers.LastActivityDate: 2023-05-29T10:27:11.067Z
Answers.LastEditDate: 2023-05-29T10:27:11.067Z
Answers.UserDisplayName: Ben I.
Answers.Body: <p>In statistics and data science, there are many real-world applications where for loops make sense. One of the simplest examples that they can do themselves is calculating the arithmetic average or mean of a group of numbers in something like an array, a vector, a list, etc. Or finding the max/min values. Or sorting the values. And so on.</p>
  <p>Looping through files is another one with tons of applications.</p>
  <p>For people interested in eventually learning about computer graphics, there's looping through the pixels of an image or even the screen.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-28T15:34:35.137Z
Answers.LastActivityDate: 2023-05-28T15:34:35.137Z
Answers.UserDisplayName: anjama
Answers.Body: <p>There are a bunch of real-life algorithms that can be represented using for loops. Some examples:</p>
  <ul>
  <li><p>Emptying your suitcase in an orderly manner after returning from a journey:</p>
  <pre class="lang-py prettyprint-override"><code>for item in suitcase:
      destination = designated_place(item)
      item.move(destination)
  
  suitcase.move(designated_place(suitcase))
  </code></pre>
  </li>
  <li><p>Remove a specific card from a deck:</p>
  <pre class="lang-py prettyprint-override"><code>for card in deck:
      if card == ACE_OF_SPADES:
          deck.remove(card)
          break
  </code></pre>
  </li>
  <li><p>Disposing of a bunch of cardboard boxes of different sizes into a distant garbage bin:</p>
  <pre class="lang-py prettyprint-override"><code>pile_of_flattened_boxes = pile()
  for box in boxes:
      for other_box in boxes:
          if box &lt; other_box:
              box.flatten()
              pile_of_flattened_boxes.add(box)
              break
      else:
          largest_box = box
  
  for box in pile_of_flattened_boxes:
      largest_box.add(box)
  
  largest_box.move_to(garbage)
  largest_box.empty_into(garbage)
  largest_box.flatten()
  garbage.add(largest_box)
  </code></pre>
  </li>
  </ul>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T11:05:52.110Z
Answers.Text: Explaining for loop and using a break? C'mon, this should be basic stuff.
Answers.UserDisplayName: Marian Paździoch
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T11:22:05.493Z
Answers.Text: @MarianPaździoch: I am not entirely sure what you are aiming at.
Answers.UserDisplayName: Wrzlprmft
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-28T09:47:20.397Z
Answers.LastActivityDate: 2023-05-28T09:54:04.877Z
Answers.LastEditDate: 2023-05-28T09:54:04.877Z
Answers.UserDisplayName: Wrzlprmft
Answers.Body: <p>Given it is to students.. rollcall?</p>
  <pre><code>for i from 0 to num_students
     print &quot;${students[i]}!?&quot; 
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T21:40:14.840Z
Answers.LastActivityDate: 2023-05-29T21:40:14.840Z
Answers.UserDisplayName: Karthik T
Answers.Body: <p>Sometimes, people press the caps lock key on a computer keyboard.</p>
  <p>Other times, people write in all lower case.</p>
  <p>There are <a href="https://convertcase.net/" rel="nofollow noreferrer">websites</a> where people copy and paste their text to fix it quickly instead of re-typing everything with their fingers.</p>
  <p>The owners of such websites are paid money to publish advertisements in the left and right margin of the website.</p>
  <p>The following python script will convert any string into TitleCase.</p>
  <p>For example, if you make a header on Stack Exchange, you might want to make the leftmost letter in each word capitalized unless the word contains three or fewer characters.</p>
  <pre><code># A Guide on For Loops #
  </code></pre>
  <p>Below is the for-loop written in python:</p>
  <pre class="lang-python prettyprint-override"><code>olist = list() 
  
      for iword in iwords:
          # `oword` is output word
          if len(iword) &gt; 3:
              oword = iword[0].upper() + iword[1:].lower()
          else:
              oword = iword.lower()
          olist.append(oword)
      
      space = &quot; &quot;
      owords = space.join(olist)
  </code></pre>
  <p>Is we embellish a little bit, we might get the following:</p>
  <pre class="lang-python prettyprint-override"><code># output list
  
  def convert_to_title_case(iiwords:str):
      &quot;&quot;&quot;
      &quot;&quot;&quot;
      
      # begin code to convert strings and lists alike into strings 
      iwords = iiwords 
      if hasattr(iwords, &quot;__iter__&quot;):
          iwords = &quot;&quot;.join(str(x) for x in iwords)
      iwords = str(iwords)
      iwords = iter(iwords)
      # end code to conert strings a list into strings  
  
      olist = list() 
  
      for iword in iwords:
          # `oword` is output word
          if len(iword) &gt; 3:
              oword = iword[0].upper() + iword[1:].lower()
          else:
              oword = iword.lower()
          olist.append(oword)
      
      # chr(32) is a single space character 
      # chr(9)  is a tab character 
      owords = chr(32).join(olist)
      
      return owords 
  </code></pre>
  <p>Below, we see the code being tested:</p>
  <pre class="lang-python prettyprint-override"><code># input text
  itext = &quot;A BoOk On YuUcA PlAnTs of NoRTH AND SOUTH aMERICA&quot;
  # aka, A Book on Environmentally Friendly Alternative to
  #     * Ballpoint Pens
  #     * Paint Brushes for outlines of cartoon characters
  #     * Paint Brushes for Continous Line Drawings and One-Line Drawings 
  #     * Background Art Having Lots of Dry Grass Growing   
  
  # input words
  iwords = itext.split()
  
  # fix the capitalization of words
  owords = convert_to_title_case(iwords)
  
  # display the final results 
  print(owords)
  
  # HOW TO SEND SOMEWHERE OTHER THAN THE SCREEN YOU SEE WITH YOUR EYEBALLS
  #  
  # MAYBE SAVE STUFF TO FILE 
  #
  # import io
  # ostrm = io.StringIO()
  # print(owords, file=ostrm)
  # ostrm.close() 
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-28T00:31:03.647Z
Answers.LastActivityDate: 2023-05-28T00:31:03.647Z
Answers.UserDisplayName: Samuel Muldoon
Answers.Body: <p>Read the student list to them.</p>
  <pre><code>For every student on the list  
    Is the student present? Yes/No
  </code></pre>
  <p>This is a simple classroom example of a for loop.</p>
  <p>If you were asked to showcase a while() loop, have them imagine having a bag of chips</p>
  <pre><code>While bag not empty
    Eat one chip 
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T10:17:34.010Z
Answers.LastActivityDate: 2023-05-30T10:17:34.010Z
Answers.UserDisplayName: Thomas
Answers.Body: <p>Loading suitcases onto a train might work:</p>
  <pre><code>for entry in one through the number of suitcases on the platform {
      load the entry'th suitcase onto the train
  }
  </code></pre>
  <p>But how about this:</p>
  <pre><code>while there is a suitcase on the platform {
      load suitcase onto the train
  }
  </code></pre>
  <p><code>while</code> loops, after all, are just syntactic sugar on top of <code>for</code> loops.</p>
  <p>Or how about this:</p>
  <pre><code>for each suitcase on the platform {
      load suitcase onto the train
  }
  </code></pre>
  <p><code>for each</code> loops, after all, are just syntactic sugar on top of <code>while</code> loops.</p>
  <p>Plain <code>for</code> loops are rare in modern software, because we have better tools available in modern languages. Why not prepare students for real-life code by teaching them the simplest, most powerful, <em>and</em> most intuitive loop structure?</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T08:28:33.990Z
Answers.Text: It appears to me that there is an underlying difference here. The two `for` versions tag all the items (sequenced for the "n'th item", listed for the "each" item) up front. The `while` version just takes a random item each time. In the practical version, it is way easier to see that the platform has become empty, than to remember the sequence in which you noticed the original items, or the unique items that were present before you started taking them away. (In practice of course, you take the largest items first, because they stack better in the luggage van.)
Answers.UserDisplayName: Paul_Pedant
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T18:59:46.650Z
Answers.Text: You could get different behavior of the for-each and while loops, as the set from which "each" is drawn only typically gets evaluated once at the start of the loop. In your example, the while loop will continue to load suitcases until the platform is empty, but the for loop may only load the suitcases that were present at the start of the loop. If more suitcases get dropped off after you start the loop, the while loop will get them but the for loop may not.
Answers.UserDisplayName: Nuclear Hoagie
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-28T10:27:28.643Z
Answers.LastActivityDate: 2023-05-28T10:27:28.643Z
Answers.UserDisplayName: l0b0
Answers.Body: <p>Are you teaching programming in a specific language, or computer science?</p>
  <p>If the latter, then I would start with the concept of a functional mapping applied to the elements of a set: for example, given a set containing the names of countries, you want a set containing pictures of their flags. Then you explain that in low-level procedural languages, there is a for-loop which is commonly used to implement functional mappings of that kind; though it can also be used in other ways, because it may process the elements of the set in a defined order, and it can be stateful. So it can be used for an abstract &quot;reduce&quot; operation as well as an abstract &quot;map&quot; operation.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-28T14:15:39.557Z
Answers.Text: I'm not involved in teaching, but I'd think teaching forEach and map before something involving indexes makes sense in this day and age. Starting with the most complicated and general case because that came first historically or that's needed to implement a map function seems wrong.
Answers.UserDisplayName: JollyJoker
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-28T14:47:48.540Z
Answers.Text: From an abstract computer science perspective, for as described in the OP is just a special case of foreach, operating over numeric ranges. (To the point that at least a couple of modern languages such as rust and kotlin, don't bother with traditional for loops).
Answers.UserDisplayName: user1937198
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-28T11:38:08.627Z
Answers.LastActivityDate: 2023-05-28T11:38:08.627Z
Answers.UserDisplayName: Michael Kay
Answers.Body: <p>A straightforward example would be calculating a factorial:</p>
  <pre><code>int factorial = 1;
  for (int i=1; i&lt;=n; i++)
  {
      factorial = factorial * i;
  }
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T19:05:19.160Z
Answers.LastActivityDate: 2023-05-30T19:05:19.160Z
Answers.UserDisplayName: Cristobol Polychronopolis
Answers.Body: <p>Any time you repeat a task and keep count of the number of iterations to make sure you do it the right amount of times, you're effectively performing a for loop.</p>
  <p>For example (pun intended) if I need to pick 12 carrots from the garden I will count up in my head every time I pick one until I reach 12. I am affectively performing</p>
  <pre><code>for (int numCarrots=0; numCarrots&lt;12; numCarrots++)
  {
      pickCarrot();
  }
  </code></pre>
  <p>This is different from a while loop, because I am not counting the number of carrots in my hand each time I add another one.</p>
  <p>Another example could be counting money. If you want to count \$1000 in \$10 bills, it's often easier to make to count 10 stacks of 10 bills than counting 100 bills without mistakes.</p>
  <pre><code>for (int hundreds=0; hundreds&lt;10; hundreds ++)
  {
      for (int bills=0; tens&lt;10; tens++)
      {
           addBill();
      }
  }
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T14:46:54.153Z
Answers.LastActivityDate: 2023-05-30T14:46:54.153Z
Answers.UserDisplayName: Aubreal
Answers.Body: <pre><code>foreach (<span class="math-container">$item in $</span>HoneyDoList)
  {
      $item.do()
  }
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T17:42:47.820Z
Answers.LastActivityDate: 2023-05-29T17:42:47.820Z
Answers.UserDisplayName: RonJohn
Answers.Body: <p>Imagine noting down all the purchases you made in a month in some journal. Adding the cost of each purchase to a running total via calculator can be thought of via for-loop: iterate over each element and add to some defined variable.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-31T05:20:21.103Z
Answers.LastActivityDate: 2023-05-31T05:20:21.103Z
Answers.UserDisplayName: Aditya Tadimeti
Answers.Body: <p>A classic example would be a simple traffic control signal, using for loops for delays to control the cycling of the signals at a 4 way intersection. This could be possible with a simple 8 bit processor (such as 8051) and not require any ram, just rom and registers, and input and output pins connected to sensors and switches. A true state machine where the state would be which for loop the controller was currently at.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T01:39:44.017Z
Answers.LastActivityDate: 2023-05-30T01:39:44.017Z
Answers.UserDisplayName: rcgldr
Answers.Body: <p>Ah well, why not. :)</p>
  <pre><code>int age;
  for(age = 0; age &lt; 90; age++)
  {
      switch (arr[i])
      {
      case 0 ... 6:
          Cry();
          ShitPants();
          break;
      case 7 ... 18:
          School();
          break;
      case 19 ... 70:
          Work();
          break;
      case 71 ... 80:
          Reminiscing(&quot;Back in my day...&quot;);
          break;  
      case 81 ... 90:
          Cry();
          ShitPants();
          break;  
      default:
          Matrix.Broken(&quot;You managed to brake the system.&quot;);
          break;
      }
  }
  Die();
  </code></pre>
  <p>Or just calculate your average grade. (Not sure about the american folks, but over here we grade 1 to 10)</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-31T07:18:03.870Z
Answers.LastActivityDate: 2023-05-31T09:16:23.160Z
Answers.LastEditDate: 2023-05-31T09:16:23.160Z
Answers.UserDisplayName: Bas Visscher
Answers.Body: <p>Actually, every hand (hour, minute and second) in a clock is a (nested) for loop which does an action of rotating a hand by certain degrees once every second</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T10:34:49.560Z
Answers.Text: A nested for loop would be a tricky way to implement it, and full of traps that students probably won't see right away. I wouldn't recommend implementing a clock that way, and I wouldn't recommend making your earliest class examples nested, either.
Answers.UserDisplayName: Ben I.
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T19:58:07.150Z
Answers.Text: @BenI. A nested for loop is how I implemented a lovely analog clock back on ZX Spectrum when I was a wee lad. Three input statements to get hours, minutes, seconds, then a bunch of nested for loops that I painstakingly "tuned" so they'd keep the time with reasonable accuracy. After a week of tweaking (kids got lots of time back then), it would be off by less than half a minute after 24 hours. I certainly wasn't aware of the pitfalls back then, and can't quite figure what would be the pitfalls today. After 12 hours the top loop ended and there was a goto to start it again...
Answers.UserDisplayName: Kuba hasn't forgotten Monica
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T01:54:54.770Z
Answers.Text: @Kubahasn'tforgottenMonica There are two that I see.  If, at 6:30 your hour hand is facing the 6 instead of halfway between the 6 and the 7, then you have moved past one of them.  However, a true analog clock is much more similar to a single for-loop (the motor), which runs three processes at each tick,, which is how the hour hand ends up so nicely between the two hours. I don't believe that you can reasonably accomplish this with a thrice-nested for loop. The secondary trap is about threading, but I wouldn't fuss much about that one with early students.
Answers.UserDisplayName: Ben I.
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-28T13:32:24.517Z
Answers.LastActivityDate: 2023-05-28T13:32:24.517Z
Answers.UserDisplayName: Akash Shanmugaraj
Answers.Body: <p>(Inefficient) Sorting is a/several for-loop(s). Look through all books in the library and find all where the name of the author begins with A. Loop through all &quot;A-books&quot; and find all where the second character of the name is B, rinse and repeat.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T22:12:47.660Z
Answers.Text: BTW, that algorithm is like a bad version of Bucket Sort since you loop 26 times instead of once to distribute inputs to buckets.  Bucket Sort is similar to Radix Sort but not based on fixed-length keys.  I think using a sorting algorithms as an example would be a big distraction from the part you wanted to focus on (loop structure), since sorting is another major topic in computer science.  Unless that's where you were going next, into non-comparison-based sort algorithms.
Answers.UserDisplayName: Peter Cordes
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T22:38:03.323Z
Answers.LastActivityDate: 2023-05-29T22:38:03.323Z
Answers.UserDisplayName: d-b
Answers.Body: <p>Say you have a class with 31 students and you want to split them into 5 groups.</p>
  <p>You tell the leftmost student of the first row to say 1, then the next person to the right 2, then 3, then 4, then 5, and then the next one says 1 again, and so on.</p>
  <p>That's a for loop that you can do and also execute while explaining it to the class.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T09:59:43.333Z
Answers.LastActivityDate: 2023-05-29T10:38:31.417Z
Answers.LastEditDate: 2023-05-29T10:38:31.417Z
Answers.UserDisplayName: encryptoferia
Answers.Body: <p>If you work at a zen university you can give your student a live implementation of the following code:</p>
  <pre><code>while(answer(&quot;Is this a loop?&quot;)!=&quot;yes&quot;) cane.strike(student);
  </code></pre>
  <p>At any other place, just asking this question repeatedly several times should work. If the student does not get it, I would explain the joke after several failed attempts.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T21:38:18.247Z
Answers.LastActivityDate: 2023-05-30T21:38:18.247Z
Answers.UserDisplayName: cookie
Answers.Body: <h4>Reading a book</h4>
  <p>Reading a book is probably the easiest example.</p>
  <pre><code>int numPages = myBook.PageCount();
  for (int page = 1; page &lt;= numPages; page++)
  { 
      Literacy.ReadPage(myBook.Pages[page]);
  }
  </code></pre>
  <p>This example also naturally displays <em>nested</em> for loops. Each page has a set of lines to iterate over, each line has a set of words, and each word has a set of characters. You can even expand the nesting in the opposite direction - multiple books might be contained in a shelf, multiple shelves might be contained in a library, and multiple libraries might be contained in a library consortium.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T13:18:02.803Z
Answers.Text: I wonder if that would be better as an example of a while (or do) loop? I start reading a book and turn pages until I reach the end. The page numbers and how many of them there are aren't involved. Well, for fiction, anyway.
Answers.UserDisplayName: Andrew Morton
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T19:08:09.090Z
Answers.Text: While-loop is good when the end of the loop is not concrete. If the loop is satisfied before reaching the end of items in an array or if some other condition is met. Do-while means you must do at least once. Be careful with this since sometimes you may never need to do it at all. For-loops are great when there is a number increment/decrement and changes in the block have little to no effect on condition to continue the loop.
Answers.UserDisplayName: Esaith
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T22:43:36.677Z
Answers.Text: Not really a good example. Last pages of a book could be glossary or index, ads for author's other books... And the end may not necessarily on the last pages, as in "Choose your own adventure" books. You don't read a preset amount of pages - you read until the end.
Answers.UserDisplayName: mgarciaisaia
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T01:04:03.857Z
Answers.LastActivityDate: 2023-05-29T01:10:34.957Z
Answers.LastEditDate: 2023-05-29T01:10:34.957Z
Answers.UserDisplayName: Robert Columbia
Answers.Body: <p>Dealing cards in a poker game.</p>
  <pre><code>for i from 1 to 5: # 5 cards in a hand
      for each player:
          deal a card to the player
  </code></pre>
  <p>And then playing the game is also like a <code>for</code> loop. You loop around the table, giving each player an opportunity to make a bet or fold. But this might be better done using a <code>while</code> loop rather than a <code>for</code> loop.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T12:46:28.263Z
Answers.Text: Everyone getting their turn is manifestly *not* a `for` loop.  It's this: `while (!game_over) {current_player plays; current_player := next_player}`
Answers.UserDisplayName: RonJohn
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T13:01:13.520Z
Answers.Text: @RonJohn Possibly, although it could be a for-loop with a `break` when a winner is declared.
Answers.UserDisplayName: Barmar
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-29T13:02:54.147Z
Answers.Text: But I've added a comment about using `while` instead.
Answers.UserDisplayName: Barmar
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T09:38:14.163Z
Answers.Text: @JanusBahsJacquet of course dealing and playing are two separate loops.  What makes you think I said there are?
Answers.UserDisplayName: RonJohn
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T10:01:14.113Z
Answers.Text: @RonJohn Sorry, I must have read the answer too quickly – I completely missed the first sentence after the code block and read the whole thing as being about dealing.
Answers.UserDisplayName: Janus Bahs Jacquet
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-30T12:33:22.177Z
Answers.Text: @RonJohn some games are played for a given number of turns; in this case the comparison to a for-loop seems to hold.
Answers.UserDisplayName: Jumboman
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-31T00:27:21.437Z
Answers.Text: @RonJohn That's an implementation detail. In Python, I often use something like `for player in itertools.cycle([player1, player2]): ...`.
Answers.UserDisplayName: chepner
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-31T06:47:53.917Z
Answers.Text: @chepner you and I think that way, because we're programmers who accept `for` loops.  But `while ... do ...` and `do ... while` loops fit better in natural language.
Answers.UserDisplayName: RonJohn
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-31T12:08:42.423Z
Answers.Text: And what about languages with no loops at all? Everything gets done with recursion. There's a distinction between how you *describe* a task and how you actually implement that task in any given language.
Answers.UserDisplayName: chepner
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-31T16:30:22.250Z
Answers.Text: @chepner I interpreted the question specifically about `for` loops, not iteration in general. I'd like to think that the concept of doing things repetitively is intuitive, since we see repetition all around us.
Answers.UserDisplayName: Barmar
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-31T16:32:18.897Z
Answers.Text: And notice that I expressed my answer in metacode, not something specific like C's `for` syntax.
Answers.UserDisplayName: Barmar
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-28T13:11:02.933Z
Answers.LastActivityDate: 2023-05-29T13:02:40.160Z
Answers.LastEditDate: 2023-05-29T13:02:40.160Z
Answers.UserDisplayName: Barmar
Body: <p>The example of a for-loop offered in introductory texts is often very contrived.</p>
  <p>For example, we might have:</p>
  <pre><code>for k starting at 1 and ending at 30 {
      display(A[k]);
  }
  </code></pre>
  <p>When a student asks for a real-world example, what might we give them?</p>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2023-05-29T04:04:46.600Z
Comments.Text: You may check my similar question https://cseducators.stackexchange.com/questions/6699/what-are-good-practical-labs-and-activities-for-loops
Comments.UserDisplayName: Qiulang 邱朗
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2023-05-30T00:02:23.557Z
Comments.Text: What do you mean by "real-world"? I've found that usually students asking this mean "when would I use a for-loop in a real-world programming job"? (in other words, "how will knowing this help me earn money?" Then less common, "what real-world non-computer task is like a for-loop"? (AKA: "I think I only learn by analogy")
Comments.UserDisplayName: Owen Reynolds
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2023-05-30T18:46:05.600Z
Comments.Text: More important is the order that you introduce them: More specialised and safe first, general and dangerous last: `foreach item in list` (used to process items in a list) →`foreach number in range` (used when you need to do something multiple times, with a counting number, and option 1 won't do it) → `forever` (used to do something forever) → `while` (used when all else fails). I may have missed some.
Comments.UserDisplayName: ctrl-alt-delor
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2023-05-31T07:45:29.877Z
Comments.Text: Everybody who asks stupid questions like this is asked to come forward; then you iterate through them and give each one a spanking. Oh, I forgot: There are no stupid questions, right. Bummer.
Comments.UserDisplayName: Peter - Reinstate Monica
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2023-11-16T06:17:53.777Z
Comments.Text: A _real_ real world example: for the first 100 visitors who purchase stuff on a site on Black Friday, every item gets 70% discount.
Comments.UserDisplayName: Nobody
Tags: <code-example>
Title: What is a real-world example of a for-loop?
ThreadText: # What is a real-world example of a for-loop?
  
  (Asked by: username_0 on 2023-05-28)
  
  The example of a for-loop offered in introductory texts is often very contrived.
  
  For example, we might have:
  
  ```
  for k starting at 1 and ending at 30 {
      display(A[k]);
  }
  
  ```
  
  When a student asks for a real-world example, what might we give them?
  
  **Tags:** code-example
  
  > **Comments:**
  > **username_1**: You may check my similar question https://cseducators.stackexchange.com/questions/6699/what-are-good-practical-labs-and-activities-for-loops  
  > **username_2**: What do you mean by "real-world"? I've found that usually students asking this mean "when would I use a for-loop in a real-world programming job"? (in other words, "how will knowing this help me earn money?" Then less common, "what real-world non-computer task is like a for-loop"? (AKA: "I think I only learn by analogy")  
  > **username_3**: More important is the order that you introduce them: More specialised and safe first, general and dangerous last: `foreach item in list` (used to process items in a list) →`foreach number in range` (used when you need to do something multiple times, with a counting number, and option 1 won't do it) → `forever` (used to do something forever) → `while` (used when all else fails). I may have missed some.  
  > **username_4**: Everybody who asks stupid questions like this is asked to come forward; then you iterate through them and give each one a spanking. Oh, I forgot: There are no stupid questions, right. Bummer.  
  > **username_5**: A _real_ real world example: for the first 100 visitors who purchase stuff on a site on Black Friday, every item gets 70% discount.  
  
  ---
  
  ## 21 answers
  
  ### Answer by username_36 on 2023-05-28. Score: 17
  
  Dealing cards in a poker game.
  
  ```
  for i from 1 to 5: # 5 cards in a hand
      for each player:
          deal a card to the player
  
  ```
  
  And then playing the game is also like a `for` loop. You loop around the table, giving each player an opportunity to make a bet or fold. But this might be better done using a `while` loop rather than a `for` loop.
  
  > **Comments:**
  > **username_22**: Everyone getting their turn is manifestly *not* a `for` loop.  It's this: `while (!game_over) {current_player plays; current_player := next_player}`  
  > **username_36**: @username_22 Possibly, although it could be a for-loop with a `break` when a winner is declared.  
  > **username_36**: But I've added a comment about using `while` instead.  
  > **username_22**: @username_37 of course dealing and playing are two separate loops.  What makes you think I said there are?  
  > **username_37**: @username_22 Sorry, I must have read the answer too quickly – I completely missed the first sentence after the code block and read the whole thing as being about dealing.  
  > **username_38**: @username_22 some games are played for a given number of turns; in this case the comparison to a for-loop seems to hold.  
  > **username_39**: @username_22 That's an implementation detail. In Python, I often use something like `for player in itertools.cycle([player1, player2]): ...`.  
  > **username_22**: @username_39 you and I think that way, because we're programmers who accept `for` loops.  But `while ... do ...` and `do ... while` loops fit better in natural language.  
  > **username_39**: And what about languages with no loops at all? Everything gets done with recursion. There's a distinction between how you *describe* a task and how you actually implement that task in any given language.  
  > **username_36**: @username_39 I interpreted the question specifically about `for` loops, not iteration in general. I'd like to think that the concept of doing things repetitively is intuitive, since we see repetition all around us.  
  > **username_36**: And notice that I expressed my answer in metacode, not something specific like C's `for` syntax.  
  
  ---
  
  ### Answer by username_32 on 2023-05-29. Score: 12
  
  #### Reading a book
  
  Reading a book is probably the easiest example.
  
  ```
  int numPages = myBook.PageCount();
  for (int page = 1; page <= numPages; page++)
  { 
      Literacy.ReadPage(myBook.Pages[page]);
  }
  
  ```
  
  This example also naturally displays *nested* for loops. Each page has a set of lines to iterate over, each line has a set of words, and each word has a set of characters. You can even expand the nesting in the opposite direction - multiple books might be contained in a shelf, multiple shelves might be contained in a library, and multiple libraries might be contained in a library consortium.
  
  > **Comments:**
  > **username_33**: I wonder if that would be better as an example of a while (or do) loop? I start reading a book and turn pages until I reach the end. The page numbers and how many of them there are aren't involved. Well, for fiction, anyway.  
  > **username_34**: While-loop is good when the end of the loop is not concrete. If the loop is satisfied before reaching the end of items in an array or if some other condition is met. Do-while means you must do at least once. Be careful with this since sometimes you may never need to do it at all. For-loops are great when there is a number increment/decrement and changes in the block have little to no effect on condition to continue the loop.  
  > **username_35**: Not really a good example. Last pages of a book could be glossary or index, ads for author's other books... And the end may not necessarily on the last pages, as in "Choose your own adventure" books. You don't read a preset amount of pages - you read until the end.  
  
  ---
  
  ### Answer by username_8 on 2023-05-28. Score: 8
  
  The conventional `for` loop (in the c-like languages, at least) is a low-level iteration structure, and there are two challenges. The first is to understand the mechanics of the thing, and the second is to grok its purpose.
  
  You are only asking about the latter, but I would caution not to dismiss the simple examples - they are the best tools for the former. Without those mechanics, there is no fluency in the mind of the budding coder, and without that fluidity, they have an uphill battle to use the idea to build later ideas.
  
  That said, for loops are great for going through an array or a string, or for iterating up to a certain predetermined point.
  
  There comes a time when you will point out that `for` loops and `while` loops are equally powerful, but have to nevertheless explain that we use the former when we want to keep all of the iteration information together at the top, which is typically when the loop is simple, incremental, and stops at a known point. For all other, more complicated situations, we tend towards `while` loops instead.
  
  > **Comments:**
  > **username_8**: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/146334/discussion-on-answer-by-ben-i-what-is-a-real-world-example-of-a-for-loop); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.  
  
  ---
  
  ### Answer by username_6 on 2023-05-29. Score: 6
  
  As a maybe overly simplistic example: Say you want to make mashed potatoes. To make it easier we'll focus on one part of the process: prepping 5 potatoes.
  
  First, you would peel one, cut it up, and place it in a pot to be boiled. Then, you would go through the same process with the second potato and continue with each potato until you are done.
  
  Ex:
  
  ```
  For Each Potato {
      peel the potato
      slice the potato
      place it in a pot
  }
  
  ```
  
  OR
  
  ```
  for potato starting at 1 and ending at 5 {
      peeled_potato = peel(potato);
      sliced_potato = slice(peeled_potato);
      place_in_pot = into_pot(sliced_potato);
  }
  
  ```
  
  Depending on your student, this may not fit culturally; however, I would argue a similarly structured recipe could be found in most cultures. And yes, I'm assuming the student understands the basic idea of a recipe.
  
  > **Comments:**
  > **username_7**: I would surely do this as at least two and probably 3 separate loops--peel all potatoes, then slice all potatoes, then put them all in the pot. Especially if you're peeling with a peeler and not a paring knife.  
  > **username_6**: That would be another way to do it.  Personally, I would do it as described to prevent the potatoes oxidizing and turning brown while I am cutting them up.  Of course, I omitted the assumption there is water in the pot to further prevent oxidization. Reference:  [link](https://www.southernliving.com/food/veggies/potatoes/how-to-keep-potatoes-from-turning-brown#:~:text=Once%20they%20have%20been%20peeled,is%20completely%20safe%20to%20eat.)  
  > **username_7**: You can put them in water between the peeling and chopping steps to prevent browning, it will still be faster if the number of potatoes is large--I think it's interesting from a CS perspective because it goes to show that the faster answer depends on what the actual loops are doing, how many iterations there are, etc. The parts of the job that machine learning can't replace yet.  
  
  ---
  
  ### Answer by username_10 on 2023-05-28. Score: 4
  
  There are a bunch of real-life algorithms that can be represented using for loops. Some examples:
  
  * Emptying your suitcase in an orderly manner after returning from a journey:
  
    ```py
    for item in suitcase:
        destination = designated_place(item)
        item.move(destination)
  
    suitcase.move(designated_place(suitcase))
  
    ```
  * Remove a specific card from a deck:
  
    ```py
    for card in deck:
        if card == ACE_OF_SPADES:
            deck.remove(card)
            break
  
    ```
  * Disposing of a bunch of cardboard boxes of different sizes into a distant garbage bin:
  
    ```py
    pile_of_flattened_boxes = pile()
    for box in boxes:
        for other_box in boxes:
            if box < other_box:
                box.flatten()
                pile_of_flattened_boxes.add(box)
                break
        else:
            largest_box = box
  
    for box in pile_of_flattened_boxes:
        largest_box.add(box)
  
    largest_box.move_to(garbage)
    largest_box.empty_into(garbage)
    largest_box.flatten()
    garbage.add(largest_box)
  
    ```
  
  > **Comments:**
  > **username_11**: Explaining for loop and using a break? C'mon, this should be basic stuff.  
  > **username_10**: @username_11: I am not entirely sure what you are aiming at.  
  
  ---
  
  ### Answer by username_9 on 2023-05-28. Score: 3
  
  In statistics and data science, there are many real-world applications where for loops make sense. One of the simplest examples that they can do themselves is calculating the arithmetic average or mean of a group of numbers in something like an array, a vector, a list, etc. Or finding the max/min values. Or sorting the values. And so on.
  
  Looping through files is another one with tons of applications.
  
  For people interested in eventually learning about computer graphics, there's looping through the pixels of an image or even the screen.
  
  
  ---
  
  ### Answer by username_12 on 2023-05-29. Score: 2
  
  Given it is to students.. rollcall?
  
  ```
  for i from 0 to num_students
     print "${students[i]}!?" 
  
  ```
  
  
  ---
  
  ### Answer by username_0 on 2023-05-28. Score: 2
  
  Sometimes, people press the caps lock key on a computer keyboard.
  
  Other times, people write in all lower case.
  
  There are [websites](https://convertcase.net/) where people copy and paste their text to fix it quickly instead of re-typing everything with their fingers.
  
  The owners of such websites are paid money to publish advertisements in the left and right margin of the website.
  
  The following python script will convert any string into TitleCase.
  
  For example, if you make a header on Stack Exchange, you might want to make the leftmost letter in each word capitalized unless the word contains three or fewer characters.
  
  ```
  # A Guide on For Loops #
  
  ```
  
  Below is the for-loop written in python:
  
  ```python
  olist = list() 
  
      for iword in iwords:
          # `oword` is output word
          if len(iword) > 3:
              oword = iword[0].upper() + iword[1:].lower()
          else:
              oword = iword.lower()
          olist.append(oword)
      
      space = " "
      owords = space.join(olist)
  
  ```
  
  Is we embellish a little bit, we might get the following:
  
  ```python
  # output list
  
  def convert_to_title_case(iiwords:str):
      """
      """
      
      # begin code to convert strings and lists alike into strings 
      iwords = iiwords 
      if hasattr(iwords, "__iter__"):
          iwords = "".join(str(x) for x in iwords)
      iwords = str(iwords)
      iwords = iter(iwords)
      # end code to conert strings a list into strings  
  
      olist = list() 
  
      for iword in iwords:
          # `oword` is output word
          if len(iword) > 3:
              oword = iword[0].upper() + iword[1:].lower()
          else:
              oword = iword.lower()
          olist.append(oword)
      
      # chr(32) is a single space character 
      # chr(9)  is a tab character 
      owords = chr(32).join(olist)
      
      return owords 
  
  ```
  
  Below, we see the code being tested:
  
  ```python
  # input text
  itext = "A BoOk On YuUcA PlAnTs of NoRTH AND SOUTH aMERICA"
  # aka, A Book on Environmentally Friendly Alternative to
  #     * Ballpoint Pens
  #     * Paint Brushes for outlines of cartoon characters
  #     * Paint Brushes for Continous Line Drawings and One-Line Drawings 
  #     * Background Art Having Lots of Dry Grass Growing   
  
  # input words
  iwords = itext.split()
  
  # fix the capitalization of words
  owords = convert_to_title_case(iwords)
  
  # display the final results 
  print(owords)
  
  # HOW TO SEND SOMEWHERE OTHER THAN THE SCREEN YOU SEE WITH YOUR EYEBALLS
  #  
  # MAYBE SAVE STUFF TO FILE 
  #
  # import io
  # ostrm = io.StringIO()
  # print(owords, file=ostrm)
  # ostrm.close() 
  
  ```
  
  
  ---
  
  ### Answer by username_13 on 2023-05-30. Score: 2
  
  Read the student list to them.
  
  ```
  For every student on the list  
    Is the student present? Yes/No
  
  ```
  
  This is a simple classroom example of a for loop.
  
  If you were asked to showcase a while() loop, have them imagine having a bag of chips
  
  ```
  While bag not empty
    Eat one chip 
  
  ```
  
  
  ---
  
  ### Answer by username_14 on 2023-05-28. Score: 2
  
  Loading suitcases onto a train might work:
  
  ```
  for entry in one through the number of suitcases on the platform {
      load the entry'th suitcase onto the train
  }
  
  ```
  
  But how about this:
  
  ```
  while there is a suitcase on the platform {
      load suitcase onto the train
  }
  
  ```
  
  `while` loops, after all, are just syntactic sugar on top of `for` loops.
  
  Or how about this:
  
  ```
  for each suitcase on the platform {
      load suitcase onto the train
  }
  
  ```
  
  `for each` loops, after all, are just syntactic sugar on top of `while` loops.
  
  Plain `for` loops are rare in modern software, because we have better tools available in modern languages. Why not prepare students for real-life code by teaching them the simplest, most powerful, *and* most intuitive loop structure?
  
  > **Comments:**
  > **username_15**: It appears to me that there is an underlying difference here. The two `for` versions tag all the items (sequenced for the "n'th item", listed for the "each" item) up front. The `while` version just takes a random item each time. In the practical version, it is way easier to see that the platform has become empty, than to remember the sequence in which you noticed the original items, or the unique items that were present before you started taking them away. (In practice of course, you take the largest items first, because they stack better in the luggage van.)  
  > **username_16**: You could get different behavior of the for-each and while loops, as the set from which "each" is drawn only typically gets evaluated once at the start of the loop. In your example, the while loop will continue to load suitcases until the platform is empty, but the for loop may only load the suitcases that were present at the start of the loop. If more suitcases get dropped off after you start the loop, the while loop will get them but the for loop may not.  
  
  ---
  
  ### Answer by username_17 on 2023-05-28. Score: 2
  
  Are you teaching programming in a specific language, or computer science?
  
  If the latter, then I would start with the concept of a functional mapping applied to the elements of a set: for example, given a set containing the names of countries, you want a set containing pictures of their flags. Then you explain that in low-level procedural languages, there is a for-loop which is commonly used to implement functional mappings of that kind; though it can also be used in other ways, because it may process the elements of the set in a defined order, and it can be stateful. So it can be used for an abstract "reduce" operation as well as an abstract "map" operation.
  
  > **Comments:**
  > **username_18**: I'm not involved in teaching, but I'd think teaching forEach and map before something involving indexes makes sense in this day and age. Starting with the most complicated and general case because that came first historically or that's needed to implement a map function seems wrong.  
  > **username_19**: From an abstract computer science perspective, for as described in the OP is just a special case of foreach, operating over numeric ranges. (To the point that at least a couple of modern languages such as rust and kotlin, don't bother with traditional for loops).  
  
  ---
  
  ### Answer by username_20 on 2023-05-30. Score: 1
  
  A straightforward example would be calculating a factorial:
  
  ```
  int factorial = 1;
  for (int i=1; i<=n; i++)
  {
      factorial = factorial * i;
  }
  
  ```
  
  
  ---
  
  ### Answer by username_21 on 2023-05-30. Score: 0
  
  Any time you repeat a task and keep count of the number of iterations to make sure you do it the right amount of times, you're effectively performing a for loop.
  
  For example (pun intended) if I need to pick 12 carrots from the garden I will count up in my head every time I pick one until I reach 12. I am affectively performing
  
  ```
  for (int numCarrots=0; numCarrots<12; numCarrots++)
  {
      pickCarrot();
  }
  
  ```
  
  This is different from a while loop, because I am not counting the number of carrots in my hand each time I add another one.
  
  Another example could be counting money. If you want to count \$1000 in \$10 bills, it's often easier to make to count 10 stacks of 10 bills than counting 100 bills without mistakes.
  
  ```
  for (int hundreds=0; hundreds<10; hundreds ++)
  {
      for (int bills=0; tens<10; tens++)
      {
           addBill();
      }
  }
  
  ```
  
  
  ---
  
  ### Answer by username_22 on 2023-05-29. Score: 0
  
  ```
  foreach ($item in $HoneyDoList)
  {
      $item.do()
  }
  
  ```
  
  
  ---
  
  ### Answer by username_23 on 2023-05-31. Score: 0
  
  Imagine noting down all the purchases you made in a month in some journal. Adding the cost of each purchase to a running total via calculator can be thought of via for-loop: iterate over each element and add to some defined variable.
  
  
  ---
  
  ### Answer by username_24 on 2023-05-30. Score: 0
  
  A classic example would be a simple traffic control signal, using for loops for delays to control the cycling of the signals at a 4 way intersection. This could be possible with a simple 8 bit processor (such as 8051) and not require any ram, just rom and registers, and input and output pins connected to sensors and switches. A true state machine where the state would be which for loop the controller was currently at.
  
  
  ---
  
  ### Answer by username_25 on 2023-05-31. Score: 0
  
  Ah well, why not. :)
  
  ```
  int age;
  for(age = 0; age < 90; age++)
  {
      switch (arr[i])
      {
      case 0 ... 6:
          Cry();
          ShitPants();
          break;
      case 7 ... 18:
          School();
          break;
      case 19 ... 70:
          Work();
          break;
      case 71 ... 80:
          Reminiscing("Back in my day...");
          break;  
      case 81 ... 90:
          Cry();
          ShitPants();
          break;  
      default:
          Matrix.Broken("You managed to brake the system.");
          break;
      }
  }
  Die();
  
  ```
  
  Or just calculate your average grade. (Not sure about the american folks, but over here we grade 1 to 10)
  
  
  ---
  
  ### Answer by username_26 on 2023-05-28. Score: 0
  
  Actually, every hand (hour, minute and second) in a clock is a (nested) for loop which does an action of rotating a hand by certain degrees once every second
  
  > **Comments:**
  > **username_8**: A nested for loop would be a tricky way to implement it, and full of traps that students probably won't see right away. I wouldn't recommend implementing a clock that way, and I wouldn't recommend making your earliest class examples nested, either.  
  > **username_27**: @BenI. A nested for loop is how I implemented a lovely analog clock back on ZX Spectrum when I was a wee lad. Three input statements to get hours, minutes, seconds, then a bunch of nested for loops that I painstakingly "tuned" so they'd keep the time with reasonable accuracy. After a week of tweaking (kids got lots of time back then), it would be off by less than half a minute after 24 hours. I certainly wasn't aware of the pitfalls back then, and can't quite figure what would be the pitfalls today. After 12 hours the top loop ended and there was a goto to start it again...  
  > **username_8**: @username_27 There are two that I see.  If, at 6:30 your hour hand is facing the 6 instead of halfway between the 6 and the 7, then you have moved past one of them.  However, a true analog clock is much more similar to a single for-loop (the motor), which runs three processes at each tick,, which is how the hour hand ends up so nicely between the two hours. I don't believe that you can reasonably accomplish this with a thrice-nested for loop. The secondary trap is about threading, but I wouldn't fuss much about that one with early students.  
  
  ---
  
  ### Answer by username_28 on 2023-05-29. Score: 0
  
  (Inefficient) Sorting is a/several for-loop(s). Look through all books in the library and find all where the name of the author begins with A. Loop through all "A-books" and find all where the second character of the name is B, rinse and repeat.
  
  > **Comments:**
  > **username_29**: BTW, that algorithm is like a bad version of Bucket Sort since you loop 26 times instead of once to distribute inputs to buckets.  Bucket Sort is similar to Radix Sort but not based on fixed-length keys.  I think using a sorting algorithms as an example would be a big distraction from the part you wanted to focus on (loop structure), since sorting is another major topic in computer science.  Unless that's where you were going next, into non-comparison-based sort algorithms.  
  
  ---
  
  ### Answer by username_30 on 2023-05-29. Score: 0
  
  Say you have a class with 31 students and you want to split them into 5 groups.
  
  You tell the leftmost student of the first row to say 1, then the next person to the right 2, then 3, then 4, then 5, and then the next one says 1 again, and so on.
  
  That's a for loop that you can do and also execute while explaining it to the class.
  
  
  ---
  
  ### Answer by username_31 on 2023-05-30. Score: 0
  
  If you work at a zen university you can give your student a live implementation of the following code:
  
  ```
  while(answer("Is this a loop?")!="yes") cane.strike(student);
  
  ```
  
  At any other place, just asking this question repeatedly several times should work. If the student does not get it, I would explain the joke after several failed attempts.
  
  
  ---
  
  