8
$\begingroup$

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?

$\endgroup$
5
  • $\begingroup$ You may check my similar question cseducators.stackexchange.com/questions/6699/… $\endgroup$ May 29, 2023 at 4:04
  • 5
    $\begingroup$ 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") $\endgroup$ May 30, 2023 at 0:02
  • 1
    $\begingroup$ 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. $\endgroup$ May 30, 2023 at 18:46
  • 2
    $\begingroup$ 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. $\endgroup$ May 31, 2023 at 7:45
  • $\begingroup$ A real real world example: for the first 100 visitors who purchase stuff on a site on Black Friday, every item gets 70% discount. $\endgroup$
    – Nobody
    Nov 16, 2023 at 6:17

21 Answers 21

17
$\begingroup$

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.

$\endgroup$
11
  • 1
    $\begingroup$ Everyone getting their turn is manifestly not a for loop. It's this: while (!game_over) {current_player plays; current_player := next_player} $\endgroup$
    – RonJohn
    May 29, 2023 at 12:46
  • 1
    $\begingroup$ @RonJohn Possibly, although it could be a for-loop with a break when a winner is declared. $\endgroup$
    – Barmar
    May 29, 2023 at 13:01
  • $\begingroup$ But I've added a comment about using while instead. $\endgroup$
    – Barmar
    May 29, 2023 at 13:02
  • 2
    $\begingroup$ @JanusBahsJacquet of course dealing and playing are two separate loops. What makes you think I said there are? $\endgroup$
    – RonJohn
    May 30, 2023 at 9:38
  • 1
    $\begingroup$ @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. $\endgroup$ May 30, 2023 at 10:01
12
$\begingroup$

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.

$\endgroup$
3
  • 3
    $\begingroup$ 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. $\endgroup$ May 30, 2023 at 13:18
  • 1
    $\begingroup$ 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. $\endgroup$
    – Esaith
    May 30, 2023 at 19:08
  • $\begingroup$ 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. $\endgroup$ May 30, 2023 at 22:43
8
$\begingroup$

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.

$\endgroup$
1
6
$\begingroup$

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.

$\endgroup$
3
  • $\begingroup$ 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. $\endgroup$ May 30, 2023 at 13:51
  • $\begingroup$ 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 $\endgroup$
    – Rakicy
    Jun 11, 2023 at 17:27
  • $\begingroup$ 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. $\endgroup$ Jun 12, 2023 at 15:38
4
$\begingroup$

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)
    
$\endgroup$
2
  • $\begingroup$ Explaining for loop and using a break? C'mon, this should be basic stuff. $\endgroup$ May 30, 2023 at 11:05
  • $\begingroup$ @MarianPaździoch: I am not entirely sure what you are aiming at. $\endgroup$
    – Wrzlprmft
    May 30, 2023 at 11:22
3
$\begingroup$

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.

$\endgroup$
2
$\begingroup$

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() 
$\endgroup$
2
$\begingroup$

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?

$\endgroup$
2
  • $\begingroup$ 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.) $\endgroup$ May 29, 2023 at 8:28
  • $\begingroup$ 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. $\endgroup$ May 30, 2023 at 18:59
2
$\begingroup$

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.

$\endgroup$
2
  • 2
    $\begingroup$ 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. $\endgroup$
    – JollyJoker
    May 28, 2023 at 14:15
  • 1
    $\begingroup$ 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). $\endgroup$ May 28, 2023 at 14:47
2
$\begingroup$

Given it is to students.. rollcall?

for i from 0 to num_students
   print "${students[i]}!?" 
$\endgroup$
2
$\begingroup$

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 
$\endgroup$
1
$\begingroup$

A straightforward example would be calculating a factorial:

int factorial = 1;
for (int i=1; i<=n; i++)
{
    factorial = factorial * i;
}
$\endgroup$
0
$\begingroup$

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

$\endgroup$
3
  • $\begingroup$ 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. $\endgroup$
    – Ben I.
    May 29, 2023 at 10:34
  • $\begingroup$ @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... $\endgroup$ May 29, 2023 at 19:58
  • 1
    $\begingroup$ @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. $\endgroup$
    – Ben I.
    May 30, 2023 at 1:54
0
$\begingroup$

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.

$\endgroup$
0
$\begingroup$
foreach ($item in $HoneyDoList)
{
    $item.do()
}
$\endgroup$
0
$\begingroup$

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

$\endgroup$
1
  • $\begingroup$ 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. $\endgroup$ May 30, 2023 at 22:12
0
$\begingroup$

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.

$\endgroup$
0
$\begingroup$

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();
    }
}
$\endgroup$
0
$\begingroup$

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.

$\endgroup$
0
$\begingroup$

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.

$\endgroup$
0
$\begingroup$

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)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.