I’ve been wondering lately what it is about loops (in computer programs) that is so hard for students to get their heads around. A college professor was telling me (back a while ago but it stuck with me) that they had assigned a program to print out the words to The Twelve Days of Christmas and had explicitly asked student to use loops. And when you think about it this is a natural for loops because of all the repetition. A good number (or bad depending on point of view) had actually submitted solutions without loops. Some of these students had previously taken and passed Advanced Placement Computer Science in high school! What’s up with that?
Clearly it is not lazy. using loops is the way lazy people would do it. (Though I like to think that there is a fine line between lazy and efficient at times) No, students had used cut and paste and a lot of typing to do this all inline.
Now loops are something we do without thinking all the time. Climbing stairs is a while loop. Think about it – we repeat the same step motions until we get to the top or bottom of the stairs. We check, usually with our eyes, to see when we are there and then change our motions. We’ve all seen what happens when people don’t check haven’t we? Blind people climbing familiar steps memorize the number of steps and effectively execute a for/next loop to do the same thing. Eating is the same. We keep putting food in our mouth until either we are full or we run out of food which ever comes first.
And yet all too often students fail to see how programming syntax allows them to do the same things in a program. I don’t get it.
Loops of course are all the same in programming. Oh the syntax is different for different types of loops and in different programming languages but basically they have the same components.
- Setting initial conditions
- Changing conditions
- Checking to see if the condition has changed such that the loop should terminate
In the middle somewhere useful work happens – giving the benefit of the doubt.
Here is a Small Basic example
Here is a C# while loop