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?
Computer Science Educators Stack Exchange is a question and answer site for those involved in the field of teaching Computer Science. It only takes a minute to sign up.
Sign up to join this communityDealing 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.
for
loop. It's this: while (!game_over) {current_player plays; current_player := next_player}
$\endgroup$
break
when a winner is declared.
$\endgroup$
while
instead.
$\endgroup$
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.
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.
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.
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)
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.
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()
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?
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 at 8:28
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.
Given it is to students.. rollcall?
for i from 0 to num_students
print "${students[i]}!?"
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
A straightforward example would be calculating a factorial:
int factorial = 1;
for (int i=1; i<=n; i++)
{
factorial = factorial * i;
}
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
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.
(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.
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.
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();
}
}
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.
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.
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)
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$