<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>

CC BY-SA 4.0
2023-05-30T13:51:40.887Z
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.
user3067860
CC BY-SA 4.0
2023-06-11T17:27:03.350Z
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.)
Rakicy
CC BY-SA 4.0
2023-06-12T15:38:59.000Z
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.
user3067860
CC BY-SA 4.0
2023-05-29T16:07:28.903Z
2023-05-29T16:07:28.903Z
Rakicy
<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>

CC BY-SA 4.0
2023-05-29T10:28:59.790Z
**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.
Ben I.
CC BY-SA 4.0
2023-05-28T02:43:01.707Z
2023-05-29T10:27:11.067Z
2023-05-29T10:27:11.067Z
Ben I.
<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>

CC BY-SA 4.0
2023-05-28T15:34:35.137Z
2023-05-28T15:34:35.137Z
anjama
<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>

CC BY-SA 4.0
2023-05-30T11:05:52.110Z
Explaining for loop and using a break? C'mon, this should be basic stuff.
Marian Paździoch
CC BY-SA 4.0
2023-05-30T11:22:05.493Z
@MarianPaździoch: I am not entirely sure what you are aiming at.
Wrzlprmft
CC BY-SA 4.0
2023-05-28T09:47:20.397Z
2023-05-28T09:54:04.877Z
2023-05-28T09:54:04.877Z
Wrzlprmft
<p>Given it is to students.. rollcall?</p>
<pre><code>for i from 0 to num_students
   print &quot;${students[i]}!?&quot; 
</code></pre>

CC BY-SA 4.0
2023-05-29T21:40:14.840Z
2023-05-29T21:40:14.840Z
Karthik T
<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>

CC BY-SA 4.0
2023-05-28T00:31:03.647Z
2023-05-28T00:31:03.647Z
Samuel Muldoon
<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>

CC BY-SA 4.0
2023-05-30T10:17:34.010Z
2023-05-30T10:17:34.010Z
Thomas
<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>

CC BY-SA 4.0
2023-05-29T08:28:33.990Z
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.)
Paul_Pedant
CC BY-SA 4.0
2023-05-30T18:59:46.650Z
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.
Nuclear Hoagie
CC BY-SA 4.0
2023-05-28T10:27:28.643Z
2023-05-28T10:27:28.643Z
l0b0
<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>

CC BY-SA 4.0
2023-05-28T14:15:39.557Z
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.
JollyJoker
CC BY-SA 4.0
2023-05-28T14:47:48.540Z
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).
user1937198
CC BY-SA 4.0
2023-05-28T11:38:08.627Z
2023-05-28T11:38:08.627Z
Michael Kay
<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>

CC BY-SA 4.0
2023-05-30T19:05:19.160Z
2023-05-30T19:05:19.160Z
Cristobol Polychronopolis
<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>

CC BY-SA 4.0
2023-05-30T14:46:54.153Z
2023-05-30T14:46:54.153Z
Aubreal
<pre><code>foreach (<span class="math-container">$item in $</span>HoneyDoList)
{
    $item.do()
}
</code></pre>

CC BY-SA 4.0
2023-05-29T17:42:47.820Z
2023-05-29T17:42:47.820Z
RonJohn
<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>

CC BY-SA 4.0
2023-05-31T05:20:21.103Z
2023-05-31T05:20:21.103Z
Aditya Tadimeti
<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>

CC BY-SA 4.0
2023-05-30T01:39:44.017Z
2023-05-30T01:39:44.017Z
rcgldr
<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>

CC BY-SA 4.0
2023-05-31T07:18:03.870Z
2023-05-31T09:16:23.160Z
2023-05-31T09:16:23.160Z
Bas Visscher
<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>

CC BY-SA 4.0
2023-05-29T10:34:49.560Z
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.
Ben I.
CC BY-SA 4.0
2023-05-29T19:58:07.150Z
@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...
Kuba hasn't forgotten Monica
CC BY-SA 4.0
2023-05-30T01:54:54.770Z
@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.
Ben I.
CC BY-SA 4.0
2023-05-28T13:32:24.517Z
2023-05-28T13:32:24.517Z
Akash Shanmugaraj
<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>

CC BY-SA 4.0
2023-05-30T22:12:47.660Z
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.
Peter Cordes
CC BY-SA 4.0
2023-05-29T22:38:03.323Z
2023-05-29T22:38:03.323Z
d-b
<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>

CC BY-SA 4.0
2023-05-29T09:59:43.333Z
2023-05-29T10:38:31.417Z
2023-05-29T10:38:31.417Z
encryptoferia
<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>

CC BY-SA 4.0
2023-05-30T21:38:18.247Z
2023-05-30T21:38:18.247Z
cookie
<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>

CC BY-SA 4.0
2023-05-30T13:18:02.803Z
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.
Andrew Morton
CC BY-SA 4.0
2023-05-30T19:08:09.090Z
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.
Esaith
CC BY-SA 4.0
2023-05-30T22:43:36.677Z
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.
mgarciaisaia
CC BY-SA 4.0
2023-05-29T01:04:03.857Z
2023-05-29T01:10:34.957Z
2023-05-29T01:10:34.957Z
Robert Columbia
<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>

CC BY-SA 4.0
2023-05-29T12:46:28.263Z
Everyone getting their turn is manifestly *not* a `for` loop.  It's this: `while (!game_over) {current_player plays; current_player := next_player}`
RonJohn
CC BY-SA 4.0
2023-05-29T13:01:13.520Z
@RonJohn Possibly, although it could be a for-loop with a `break` when a winner is declared.
Barmar
CC BY-SA 4.0
2023-05-29T13:02:54.147Z
But I've added a comment about using `while` instead.
Barmar
CC BY-SA 4.0
2023-05-30T09:38:14.163Z
@JanusBahsJacquet of course dealing and playing are two separate loops.  What makes you think I said there are?
RonJohn
CC BY-SA 4.0
2023-05-30T10:01:14.113Z
@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.
Janus Bahs Jacquet
CC BY-SA 4.0
2023-05-30T12:33:22.177Z
@RonJohn some games are played for a given number of turns; in this case the comparison to a for-loop seems to hold.
Jumboman
CC BY-SA 4.0
2023-05-31T00:27:21.437Z
@RonJohn That's an implementation detail. In Python, I often use something like `for player in itertools.cycle([player1, player2]): ...`.
chepner
CC BY-SA 4.0
2023-05-31T06:47:53.917Z
@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.
RonJohn
CC BY-SA 4.0
2023-05-31T12:08:42.423Z
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.
chepner
CC BY-SA 4.0
2023-05-31T16:30:22.250Z
@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.
Barmar
CC BY-SA 4.0
2023-05-31T16:32:18.897Z
And notice that I expressed my answer in metacode, not something specific like C's `for` syntax.
Barmar
CC BY-SA 4.0
2023-05-28T13:11:02.933Z
2023-05-29T13:02:40.160Z
2023-05-29T13:02:40.160Z
Barmar
<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>

CC BY-SA 4.0
2023-05-29T04:04:46.600Z
You may check my similar question https://cseducators.stackexchange.com/questions/6699/what-are-good-practical-labs-and-activities-for-loops
Qiulang 邱朗
CC BY-SA 4.0
2023-05-30T00:02:23.557Z
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")
Owen Reynolds
CC BY-SA 4.0
2023-05-30T18:46:05.600Z
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.
ctrl-alt-delor
CC BY-SA 4.0
2023-05-31T07:45:29.877Z
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.
Peter - Reinstate Monica
CC BY-SA 4.0
2023-11-16T06:17:53.777Z
A _real_ real world example: for the first 100 visitors who purchase stuff on a site on Black Friday, every item gets 70% discount.
Nobody
<code-example>
What is a real-world example of a for-loop?
# 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**: @JanusBahsJacquet 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:
for item in suitcase:
    destination = designated_place(item)
    item.move(destination)

suitcase.move(designated_place(suitcase))


Remove a specific card from a deck:
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:
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**: @MarianPaździoch: 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 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:
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:
# 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:
# 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**: @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.  

---

### 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.


---

