11

In an ideal teaching language

If the language directly supports them then the order to teach looping constructs seems simple.

  • Infinite loop: forever.
  • Simple finite (bounded) loop: repeat n times.
  • Bounded loops: for i in list or for i = 1...6 (I am not sure which order these two should be in).
  • Simple unbounded: while condition
  • Complex loops: all the rest.

However often the teaching language does not directly support these. This may be an argument for choosing a different language for teaching programming.

The problems that I am having

(I am teaching in Python).
I was teaching in the order I outlined for an ideal language, but are getting problems.

For an infinite loop we use while True in Python, however students ask or struggle with this. I can not explain it without explaining while condition. So pupils have to hold something that they do not understand in their head.

Similar for repeat n times in Python it is for n in range(5):, this is a lot to keep in ones head without understanding.

The question

So the question is “what to do?”. Do we start with

  • Bounded loops: for i in list:
  • Bounded loops: for i in range(n):
  • Simple unbounded: while condition:

Or do we do it some other way?

ctrl-alt-delor
  • 10,635
  • 4
  • 24
  • 54
  • This question is related, but different https://cseducators.stackexchange.com/q/4241/204 – ctrl-alt-delor Jan 29 '18 at 10:42
  • 8
    Since languages are defined recursively, it is pretty hard to teach them strictly linearly so that _nothing_ ever needs to be passed forward. This is one (not the most important) reason for a Spiral approach to teaching in which topics are first introduced in a simple way and then returned to later, both reviewing and deepening the knowledge. – Buffy Jan 29 '18 at 13:24
  • You could instead use `for(;;)` as your infinite loop example if you want to start with `for` loops. It might be easier to explain that an "infinite" loop is one that doesn't have an exit condition at the top. – IllusiveBrian Jan 29 '18 at 19:09
  • @IllusiveBrian python does not have `for(;;)`, and as you say I just have to explain that it has no exit condition, so then have to explain exit condition. Though a different approach of saying that the `;` are separators, we will look at what goes in the gaps latter, my be preferable. As there is nothing for the students to try to ignore. It is easier to ignore nothing. Unfortunately this is not an option in python. – ctrl-alt-delor Jan 29 '18 at 19:37
  • In my school, we started with C and for loop was forbidden. You dont need it so dont use it. – aloisdg Jan 30 '18 at 13:11
  • 1
    I started in a language that only had "goto". All other structures can be expressed and are ultimately executed in that paradigm. – pojo-guy Feb 02 '18 at 03:26
  • @pojo-guy Back to to low-level first or high-level first. see https://cseducators.stackexchange.com/q/3696/204 – ctrl-alt-delor Feb 02 '18 at 09:45
  • @ctrl-alt-delor Yep, it's a conumdrum. In an ideal world you would teach both simultaneously. I can already see the steam coming from the ears of prospective future programmers though. – pojo-guy Feb 02 '18 at 16:03

7 Answers7

17

I prefer to teach while loops as part of my unit on if/else statements since the syntax and thought process are virtually identical.

I then introduce for loops when teaching lists (in Python) or arrays (in Java). With for loops, language impacts which style you likely use first. With Python, I use the for item in list structure first. In Java, I use the C style (for i=0; i<...) loop first.

I don't try to introduce all styles of looping at once as I prefer to develop the concepts across units.

Ben I.
  • 32,726
  • 11
  • 68
  • 151
Bryan R
  • 508
  • 2
  • 6
  • I've seen `for`-loops introduced after seing a lot of examples of `while`-loops with a counter that is incremented once per loop, and seing the utility of a more compact way to do that. – Arthur Jan 30 '18 at 09:38
  • Makes sense. I was thinking that with an ideal language I would teach iteration before conditional. Conditional code is over used, in most programs that I have seen. I have also done a proof that you can do any thing (Turing complete) without conditionals, so long as you can loop. (also you only need 2 loops: the super loop and the container iterator). Try it for a challenge. – ctrl-alt-delor Jan 30 '18 at 10:13
8

All of the IF and Loop structures are based on two fundamental operations: Test and Branch. The only difference between an IF-Else and a Loop of any kind is whether you branch downward or back to the top. On a flow chart this just knocks you in the nose: the only difference is the arrowhead on one line.

When something so varied and complex can be reduced to such simplicity, you know that it is a fundamental idea. Teach that idea first, and then show how it is implemented in all of the various structures as you introduce each one. Now your students understand that programming is not magic, it is not about memorizing incantations and syntax: it is about simple, logical analysis of a problem, exactly how people and animals have been breaking down problem solutions in to basic steps all along. There is nothing new or surprising here, and it need not be confusing.

With this understanding, your students can absorb new structures and languages themselves, knowing that it has to be simple underneath, because circuits are simple, and people are not really able to do vastly complex things without breaking them down in to steps. Test. Branch. Done.

user4226
  • 89
  • 2
  • 1
    This is a very interesting answer. Welcome to [cseducators.se]! My only suggestion is that it might be helpful for you to draw a more direct connection between the question and the answer. – thesecretmaster Jan 29 '18 at 15:33
  • 1
    I really like this perspective, and I hadn't quite thought about it stated so simply and cleanly before. (I also don't generally teach absolute beginners, so I don't have a ton of experience having to clarify this particular idea.) This also puts a nice punctuation mark on Bryan R.'s [observation](https://cseducators.stackexchange.com/a/4271/27), "I prefer to teach `while` loops as part of my unit on `if`/`else` statements since the syntax and thought process are virtually identical." – Ben I. Jan 29 '18 at 15:54
  • While I agree that this is how they are usually implemented. This is back to the structured/un-structured high/low level argument, that you were not here for. (yes I said usually: for example on the ARM — the most popular ≥ 32bit cpu on the planet at this time — conditional and iteration are implemented different at the very low level. For a backward conditional branch of a loop the branch predictor assumes that the branch will happen. For a forward conditional of an if it is assumed not to happen. Arm also has conditional instructions. ) But thanks for contributing. – ctrl-alt-delor Jan 29 '18 at 16:09
  • 1
    "*The only difference between an IF-Else and a Loop of any kind is whether you branch downward or back to the top*" just isn't true. DO...WHILE and LOOP...UNTIL and FOR X UNTIL Y STEP Z are nothing but (very useful) syntactic sugar laid over TEST and BRANCH. – RonJohn Jan 29 '18 at 16:45
  • @RonJohn What you said is exactly what I got out of what user4226 posted. He also said that both if/else and all of the loop constructs are just test and branch. What are you saying that is different? – Ben I. Jan 29 '18 at 17:09
  • @BenI. I directly quoted this part that isn't true. Specifically, "**whether you branch downward or back to the top**" Then I explained why. Maybe I didn't do a good enough job, though: you can have loops that check the condition at the top (WHILE...DO) and you can have loops that check the condition at the bottom (DO...WHILE). However, C and it's derivatives don't have DO...WHILE, so it seems to have fallen out of favor. I agree with everything else that user4226 (and Bryan R) wrote. – RonJohn Jan 29 '18 at 19:17
  • @RonJohn Oh, I see. The quibble was about whether the jump upwards was as a result of the test, or whether it was an unconditional jump. It still seems to reduce to the same basic idea: loops involve a jump backwards while `if`s involve a jump forwards. – Ben I. Jan 29 '18 at 19:39
  • @BenI. Correct, that's my disagreement. Here's what I'm talking about: https://en.wikipedia.org/wiki/Do_while_loop and https://en.wikipedia.org/wiki/While_loop – RonJohn Jan 29 '18 at 20:36
  • @RonJohn Hm, C most certainly has a DO...WHILE construct. Did you mean that Python does not have it? – pipe Jan 30 '18 at 10:45
  • @pipe you're absolutely right. It's been a while since I've used C, and forgot about it. – RonJohn Jan 30 '18 at 14:30
  • 3
    The importance of this answer is that it emphasizes underlying concepts. I think it can *help*, not only hurt, to teach this first - *un*structured control in various forms, and then teach structured control. That presents an excellent opportunity to teach **why** structured control is preferable. IOW, more or less follow the history -- the history itself evolved the way it did for good reasons. It's not just about teaching the use of a particular language; it's about teaching what's going on - *why* we do things the way we do. The various iteration constructs did not fall from the sky. – Drew Jan 30 '18 at 15:31
  • We do iterations, not for the pleasure to do so, but as a way to compute some results (say average of an array). Unstructured control is what the computer can do, at its lower level. But what we do goes from "divide sum by size" then "compute sum by adding all values" then "use a variable with initial value 0 and add each values", and "range over all array elements" and "use an index starting from 0 etc" (if we dont have a foreach loop over collections) and LAST use a for/while/if-goto loop. We jump from the sky. – Michel Billaud Feb 07 '18 at 10:13
5

While your ideal order makes sense, you really should try to plan the course based on the limitations of the language that you're working with. In this case, instead of thinking about the different conceptual loops, you should think about the different loop syntaxes that the language provides.

In this case, the order in @Bryan R's answer (if/else -> while -> arrays -> for) makes the most sense to me. Then, once you've finished teaching all the different sytaxes for loops, you can talk about how some loops are equivalent, for example:

a = 2
i = 0
while i < 5 do
  a = a*2
  i = i+1
end
# Ends with a == 64

is the same as

a = 2
for (i = 0; i < 5; i++) {
  a = a*2;
}
# Ends with a == 64

(also, see my answer to a different loop-related question about how for loops and while loops are really the same thing)

and then show them your ideal loops, because those are a far better way to classify different types of loops than based on syntax alone, but they won't be able to see the importance of that classification until they are comfortable with the syntax for the different loops.

thesecretmaster
  • 4,785
  • 3
  • 21
  • 48
4

Perhaps you are creating a problem where none exists. You seem to be assuming that looping needs to be covered all at once and all together, rather than distributed over some some longer range interspersed with other topics.

The two fundamentally different kinds of looping are definite in which the program knows how many iterations are necessary prior to the loop and indefinite in which it does not. Those two concepts can be taught back to back so that the essential concepts are there. The others can wait a bit. Looping over a range or list can wait until you teach collections, for example. Infinite looping can be taught as either definite or indefinite (while True:...) depending on your language.

I certainly would not choose a language based solely on its direct syntactic support for all of the possible loop forms. Most of them are excluded, in fact, to keep the number of keywords in a language to a reasonable number. Once the language is Turing Complete things can be built using idioms of the language and a student needs to become familiar with that idea (idiomatic programming) in any case.

In any case, looping, like everything else should be taught in a Spiral framework in which ideas are introduced correctly but incompletely early on and then returned to, reinforced and expanded later on. This is useful when teaching programming since languages are themselves recursive and so difficult to teach strictly linearly. But a Spiral pedagogical technique is also essential due to the way the mind works and the way people learn - via reinforcement and repetition.

Therefore simple ideas of looping can come early and more complex ones later. The level of explanation changes, since the early, simple, explanations fertilize the ground for the later ones, both expanding and deepening the knowledge. Spiral is one of the fundamental Pedagogical Patterns.

Buffy
  • 35,808
  • 10
  • 62
  • 115
  • You are correct that we should not do it all at once. While I have not mentioned, the other thinks that could be interleaved, please do not take this of evidence that I would not interleave other learning. – ctrl-alt-delor Jan 29 '18 at 13:10
  • I have added a section to question to explain the problem. – ctrl-alt-delor Jan 29 '18 at 13:17
3

For an infinite loop we use while True in python, however students ask or struggle with this. I can not explain it without explaining while condition. So pupils have to hold something that they do not understand in their head.

Could you restructure this to something that makes sense to your students in plain English?

Something like:

programShouldRun = True

while programShouldRun:
    doStuff()

Call your boolean variable whatever makes sense in the context you're working in, whether that is programShouldRun, answerNotFound, fileStillHasLines, etc.

  • Hmmm. If `programShouldRun` is a variable then this isn't specifically an infinite loop. It may turn out to be, but that depends on the future possible value of the variable. Constants are possible in Python, but a deeper concept and language specific, of course. – Buffy Jan 30 '18 at 12:25
  • Yeah, that's definitely possible, though on the other hand that could be used as a lead-in to the difference between an infinite loop and one that eventually terminates. "Up until now we've said that `programShouldRun` is always `True`, but what do you think happens if we set it to `False` at the bottom of the loop?" Alternatively: "So, this program runs forever, but we want to exit when [thing we are looking for]. Does anyone have any idea about how we'd go about fixing that?" – Petter Brodin Jan 30 '18 at 13:27
  • But don't miss the point that the question was about _classifying_ loops. An infinite loop should clearly say, semantically or syntactically, that "this loop is infinite". Controlling it specifically with a variable says just the opposite. It is about the meaning of the code, not just about how it plays out. Students (and professionals) often write infinite loops by mistake, forgetting to change a condition in some way. Your technique works only in a language that can clearly specify a constant value. For example an alternate symbol for True. – Buffy Jan 30 '18 at 13:49
2

I only ever taught my fellow students but this method was the one that everyone seemed to get.

There's a track, and there's a runner, he's running forever. When you type that while in, you're telling him to do something while he runs. Then you put a condition near the while, which is almost the same thing as a hurdle that is put in on the track. The runner has to pass this hurdle each time he completes one lap around the track, that's your loop. Your loop has to pass this check every single time it starts.

Then I give an example:

While (People are watching)
    Run()

The runner will stop after all the spectators have stopped watching him at the start of the next loop. He will get to the hurdle and notice that nobody is watching him and he will lose all motivation and then fall over.

Now if we want to tell the runner to run forever, we just have to make the hurdle so low that it can't possibly be false:

While (You are running)
    Run()

This is the same thing as the following:

While (True)
    Run()

Of course, this isn't formatted for python or anything else, you can modify this to suit whatever coding language you're teaching.

I hope this helps someone.

1

Maybe you could use physical objects to help students visualize how to utilize these loops.

For example for the bounded loops: grab 5 apples, label them with some number, and show how you go through each apple (e.g., bite each of them one at a time).

For the simple unbounded, try this: put a set of brand new apples on the table, ask if there are any of them that haven't been bitten yet. If so, then bite one, then ask again and bite another non-bitten apples until all of them are bitten.

ctrl-alt-delor
  • 10,635
  • 4
  • 24
  • 54
frostshoxx
  • 111
  • 1