<p>I'm not familiar with Octave, but here are some examples we use for while loops:</p>
<ul>
<li>Collect a user's input until it is the correct type (such as asking the user for a number)</li>
<li>Find a running sum of numbers until a user inputs 0</li>
<li>A piggy bank that collects coins (represented by single-letter user inputs) that provides a total balance only after the user inputs &quot;exit&quot;</li>
<li>Play tic-tac-toe until the game is won or has reached a draw. (Note that this game is small enough that you can do it with nine variables, which gives you flexibility based on what you've covered so far with your students)</li>
<li>Play the game of Nim until a player has won, then begun a new game. (Loop in loop!)</li>
</ul>
<p>A few caveats for you: don't introduce loops inside loops at first, and when you do, use methods to break it up.  There is plenty to master in single loops.</p>
<p>I also wouldn't introduce for loops and while loops at the same time. Start with while, since for loops just jam all of the loop governance onto a single, weird line.  Let them work through loop logic in the more intuitive while structure first.</p>
<p>When you do eventually get to for loops, you can show its equivalence to <code>while</code>, and then do things like take a number range and return its sum.  Point out that the for loop is syntactic sugar just to show a loop's structure all at once, and that we tend to use it only in the simplest cases, such as when we know exactly how many iterations we want in advance.</p>

CC BY-SA 4.0
2021-12-17T21:37:21.863Z
Disagree on waiting to introduce for loops, since they're very useful for things like iterating over arrays. For instance, in python, "for var in var_list:"
nick012000
CC BY-SA 4.0
2021-12-17T22:19:07.510Z
@nick012000 I see that -- in fact, I've even taken that approach for many years.  I eventually switched to doing `while` first because I've found over the years that it helps my students avoid cognitive traps and understand better what a loop is doing.  And usefulness hardly matters when we're only talking about 2 to 3 periods before we've covered both anyway -- we certainly cover `for` loops!  I just have to make sure it all gets into their head in a sensible way.
Ben I.
CC BY-SA 4.0
2021-12-19T21:04:57.227Z
Remark 1. Your examples are largely of "temporal loops": each iteration has to follow the previous, for instance because it corresponds to a subsequent event. However, in for-loops the loop index is often extraneous: you really want to perform an action , or test a predicate, over all elements in a collection. Thus, the python `for i in whatever` or C++ `for ( auto e : collection )` are more natural than indexed loops, let alone while loops. So I would distinguish between two types of loops: strict sequences, and "for all" loops. Neither should be reduced to the other.
Victor Eijkhout
CC BY-SA 4.0
2021-12-19T21:07:17.630Z
Remark 2. If a for loop is syntactic sugar around a while loop, and you teach the latter first, shouldn't you argue that a while loop is syntactic sugar around a `if / goto` combination and teach that first? Or maybe I'm just kidding. I do think that showing some mechanism later because it can be reduced is the wrong approach. I try to teach the highest abstraction first.
Victor Eijkhout
CC BY-SA 4.0
2022-01-09T22:52:56.213Z
@VictorEijkhout I tend to point out early on that all of programming is made up, but that the CPU is more of a 'given', because we have to construct a physical thing to run a nonphysical process. That is the leap which makes programming different from everything else. The interface between transistors and a program is the 5 operations a CPU can do, and it is well worthwhile to pierce the bubble of obscurity about computers right at the start. Then there is some basis for the abstraction. Variables are unlike anything else in the universe. It is a wonder to behold.
Scott Rowe
CC BY-SA 4.0
2022-01-09T22:58:46.800Z
@ScottRowe I'm not exactly sure what you are arguing. Variables were not mentioned in any of the foregoing. But I think the CPU should stay out of elementary teaching. We have a language with a defined syntax and semantics, and that's our computer. Whether that's executed underneath by electrons, water power, or voodoo, is immaterial.
Victor Eijkhout
CC BY-SA 4.0
2022-01-09T23:08:00.077Z
@VictorEijkhout WRT remark 2, putting aside for-each loops, which are ultimately a different beast, plain vanilla `for` loops are `while` loops with the advantage of everything being declared at the top, but the (corresponding) disadvantage of having the ordering be unintuitive.  If you take the sections `for(1;2;3) {4(...)}`, your looping order becomes 1 2 4 3 2 4 3 2.  By contrast, a while loop is written in execution order. `1; while(2) {3(...) 4;}` executes as 1 2 3 4 2 3 4 2.  I think this is the primary reason I've had better luck teaching `while` first, with `for` soon after.
Ben I.
CC BY-SA 4.0
2022-01-09T23:11:55.967Z
Not to mention that the word `while` lends itself to loops in natural, everyday English in a way that `for` does not.  I think that both `for` and (eventually) `goto` can most naturally be explained from `while`, which is the most intuitive of the bunch.
Ben I.
CC BY-SA 4.0
2022-01-09T23:16:13.003Z
@VictorEijkhout I was just responding to your statement that you like to teach the highest abstraction first. Combined with your next statement, that the CPU should be kept out of elementary teaching, you have built a bridge to the absurd. I don't understand why this is not clear to educators. We should start with the germ of the idea, just as we do with language, something children can learn with no teaching at all.
Scott Rowe
CC BY-SA 4.0
2022-01-09T23:22:36.750Z
@ScottRowe We don't teach language beginning with word roots.  What are you talking about?  We start with the simplest point of entry, and then work our way *out* from there. Babies start with conversational "aaaa", then move on to phonemes, then get a few key words, and then develop vocabulary for a long time with no lower-level understanding of diphthongs, fricatives, vowels, consonants, etymologies, word roots, or the neural basis of language.  In other words, they get NONE of the "germ of the idea" for a very long time. You may try to teach it to them at the start, but good luck with that.
Ben I.
CC BY-SA 4.0
2022-01-09T23:28:07.630Z
We are hard-wired to learn language essentially in that order.  Start with the most intuitive, at whatever level of abstraction that is, and then slowly expand your understanding.  You make these claims, but you did not start learning about computers with Turing Machines and Von Neumann architectures. Just like the rest of us, you began at the level of abstraction that best reflected whatever computer you, personally, started on, because that was what was open to you at the time.  And then you explored out from there, because that's what we all do.
Ben I.
CC BY-SA 4.0
2022-01-09T23:53:30.590Z
@ScottRowe I'm with Ben on the levels of abstraction thing. I mostly teach C++, and there are people who approach that as "C with extras", teaching first C and the basic mechanisms, ,and then C++ and how it gives a higher level of abstraction over the C mechanisms. I completely disagree with that, and I have some very reputable people to back me up. While it's not entirely analogous, I feel that way about your notions of starting with an understanding of the CPU too. I only discuss the CPU in cases like when students get integer overflow, then I tell them about 32-bit ints.
Victor Eijkhout
CC BY-SA 4.0
2022-01-10T00:51:21.937Z
I would think that students would like to know how computers work. Didn't you?
Scott Rowe
CC BY-SA 4.0
2022-01-10T01:50:53.127Z
@ScottRowe Are you dodging on purpose?  The argument isn't about whether to cover it. The issue is about *when* to cover it.  Before a graduate school level, there are no topics that we learn from first principles, in computer science, or out of it.  That's not how the human brain works.  Not for language, not for numbers, not for song, not for writing... we don't begin at the underlying foundation.  We begin at the easiest point of entry, and then we explore out.  Computer Science is no different, because the wetware is no different.
Ben I.
CC BY-SA 4.0
2022-01-10T01:53:23.590Z
I teach processor design and architecture.  I take my kids all the way down to the wires and the boolean gates, and they build an entire processor that way.  I don't argue against teaching low-level stuff, I think it's very important.  But it's not a class for freshmen.  I take them after they've done programming and assembly first.
Ben I.
CC BY-SA 4.0
2022-01-10T10:54:39.493Z
Ben, I'm sorry that I keep bringing up this question and always get the same mystifying responses from most everyone. Today I was thinking that you-all are perceiving what I say from an Academic point of view. That's not what I'm saying at all. I am saying, how do you tell a kid how a computer, an electrical machine that can answer questions, can do that. Just like, what makes a car go, or, why do planes fly. Have you lost your memory of having that thought? Without some satisfying answer early on, I would have stuck with electronics, where the few books I found actually explained things.
Scott Rowe
CC BY-SA 4.0
2022-01-10T11:04:55.017Z
I watched the moon landing and I watched Nixon resign. If someone wasn't direct and to the point with me when I was a child, I disregarded them and went on to get the answers myself. I guess kids now are not that way.
Scott Rowe
CC BY-SA 4.0
2022-01-10T11:52:27.470Z
@ScottRowe If a total beginner asked me the question (they usually don't), I would tell them that, as crazy as it sounds, it all comes down to true and false, and, or, and not, and that if they find that intriguing, they should... then I would tell them the sequence of courses they need to arrive at processors at my school.  I've a flair for the dramatic! I like to think that I make such things sound intriguing in person. If you had been my student, I don't think you would have abandoned ship!  
Ben I.
CC BY-SA 4.0
2021-12-16T12:33:23.813Z
2021-12-16T12:33:23.813Z
Ben I.
<p>The collatz conjecture is a great example of a while loop:</p>
<ul>
<li>start with any number</li>
<li>if it's even, divide by 2</li>
<li>if it's odd, times three and add 1</li>
<li>stop if you ever reach 1. (what happens if you continue?)</li>
</ul>
<p>The conjecture that you'll always reach 1 is just about the easiest to explain, hardest to prove, statement in math. As in: still open.</p>
<p>For students to explore:</p>
<ul>
<li>What's the longest route to 1 you can find?</li>
<li>What's the biggest increase from the starting point?</li>
<li>Et cetera.</li>
</ul>

CC BY-SA 4.0
2021-12-17T22:23:32.360Z
2022-01-04T04:40:12.260Z
2022-01-04T04:40:12.260Z
Victor Eijkhout
<blockquote>
<p>I struggle in finding exercises and examples which could be suitable for them.</p>
</blockquote>
<p>See: <a href="https://runestone.academy/runestone/default/user/login?_next=/runestone/default/index" rel="nofollow noreferrer">Runestone Academy</a>. Also see <a href="https://csawesome.runestone.academy/runestone/books/published/csawesome/index.html" rel="nofollow noreferrer">CSAwesome</a>. CSAwesome is used by hundreds of teachers in the US.</p>

CC BY-SA 4.0
2021-12-16T09:42:39.270Z
2021-12-16T09:42:39.270Z
Guy Coder
<p>Look at the scratch resources at NCCE.</p>
<p>Scratch is a graphical block based language designed for kids to learn programming.</p>
<p>The National Centre for Computing Education, have produced various teaching resources. As an experienced programmer, and new teacher, I used these as is the first time, then started adapting them.</p>
<p><a href="https://teachcomputing.org/curriculum/key-stage-3" rel="nofollow noreferrer">https://teachcomputing.org/curriculum/key-stage-3</a></p>

CC BY-SA 4.0
2021-12-17T18:36:12.897Z
I'm not based in the UK but I love teachcomputing.org.  It's such a tremendous resource!
Ben I.
CC BY-SA 4.0
2021-12-17T18:24:28.027Z
2021-12-17T18:24:28.027Z
ctrl-alt-delor
<p>When I was teaching myself programming at age 14 I used nested For loops to make shapes on a text screen. For example, input a width and height and make a rectangle. Then modify the code to make it hollow. Then draw triangles, then diamonds.</p>
<p>Eventually I had a program that continuously chose shapes and sizes at random (kids love random stuff) which scrolled up the screen indefinitely. It was easy to get started and had enough challenge to be interesting.</p>

CC BY-SA 4.0
2022-01-04T02:43:13.780Z
2022-01-04T02:43:13.780Z
Scott Rowe
<p>I teach in a secondary, first grade, school in Italy. The kids are 13 years old, on last year before second grade. I am teaching them the very basic of programming. Last year we did some flowcharts algorithms, this year we started code programming in Octave. I've teached them how to make simple algorithms with if/else and now I'm going to go for the for and while loops, but I struggle in finding exercises and examples which could be suitable for them, apart from cumulative sums/differences. Consider that they are very young and have just basic math knowledge. They don't even know what a matrix is, but I can overcome that by explaining at least a monodimensional one. But really I can use some help on exercise with for and while. Any help?</p>

CC BY-SA 4.0
2021-12-28T07:55:26.117Z
I asked a similar question https://cseducators.stackexchange.com/questions/6699/what-are-good-practical-labs-and-activities-for-unnested-loops
Qiulang 邱朗
CC BY-SA 4.0
2021-12-28T15:06:47.083Z
Do you know [Processing](https://processing.org/)? I do think Octave is too difficult /too math oriented for 12/13 kids. In Prcessing, basic ideas and notions of programming can be visualized by animated geometry examples. It was deveolped in a school of art with the idea of being a didactical tool too. (scrivo dall'Italia anche io :-) ).
mario
CC BY-SA 4.0
2022-01-08T23:55:34.023Z
How is it possible, in Italy or anywhere else, that standard examples aren't available to all teachers?
Robbie Goodwin
<looping>
For and while loops examples for 12-13 years old class
# For and while loops examples for 12-13 years old class

(Asked by: username_0 on 2021-12-16)

I teach in a secondary, first grade, school in Italy. The kids are 13 years old, on last year before second grade. I am teaching them the very basic of programming. Last year we did some flowcharts algorithms, this year we started code programming in Octave. I've teached them how to make simple algorithms with if/else and now I'm going to go for the for and while loops, but I struggle in finding exercises and examples which could be suitable for them, apart from cumulative sums/differences. Consider that they are very young and have just basic math knowledge. They don't even know what a matrix is, but I can overcome that by explaining at least a monodimensional one. But really I can use some help on exercise with for and while. Any help?

**Tags:** looping

> **Comments:**
> **username_1**: I asked a similar question https://cseducators.stackexchange.com/questions/6699/what-are-good-practical-labs-and-activities-for-unnested-loops  
> **username_2**: Do you know [Processing](https://processing.org/)? I do think Octave is too difficult /too math oriented for 12/13 kids. In Prcessing, basic ideas and notions of programming can be visualized by animated geometry examples. It was deveolped in a school of art with the idea of being a didactical tool too. (scrivo dall'Italia anche io :-) ).  
> **username_3**: How is it possible, in Italy or anywhere else, that standard examples aren't available to all teachers?  

---

## 5 answers

### Answer by username_4 on 2021-12-16. Score: 3

I'm not familiar with Octave, but here are some examples we use for while loops:

* Collect a user's input until it is the correct type (such as asking the user for a number)
* Find a running sum of numbers until a user inputs 0
* A piggy bank that collects coins (represented by single-letter user inputs) that provides a total balance only after the user inputs "exit"
* Play tic-tac-toe until the game is won or has reached a draw. (Note that this game is small enough that you can do it with nine variables, which gives you flexibility based on what you've covered so far with your students)
* Play the game of Nim until a player has won, then begun a new game. (Loop in loop!)

A few caveats for you: don't introduce loops inside loops at first, and when you do, use methods to break it up. There is plenty to master in single loops.

I also wouldn't introduce for loops and while loops at the same time. Start with while, since for loops just jam all of the loop governance onto a single, weird line. Let them work through loop logic in the more intuitive while structure first.

When you do eventually get to for loops, you can show its equivalence to `while`, and then do things like take a number range and return its sum. Point out that the for loop is syntactic sugar just to show a loop's structure all at once, and that we tend to use it only in the simplest cases, such as when we know exactly how many iterations we want in advance.

> **Comments:**
> **username_5**: Disagree on waiting to introduce for loops, since they're very useful for things like iterating over arrays. For instance, in python, "for var in var_list:"  
> **username_4**: @username_5 I see that -- in fact, I've even taken that approach for many years.  I eventually switched to doing `while` first because I've found over the years that it helps my students avoid cognitive traps and understand better what a loop is doing.  And usefulness hardly matters when we're only talking about 2 to 3 periods before we've covered both anyway -- we certainly cover `for` loops!  I just have to make sure it all gets into their head in a sensible way.  
> **username_6**: Remark 1. Your examples are largely of "temporal loops": each iteration has to follow the previous, for instance because it corresponds to a subsequent event. However, in for-loops the loop index is often extraneous: you really want to perform an action , or test a predicate, over all elements in a collection. Thus, the python `for i in whatever` or C++ `for ( auto e : collection )` are more natural than indexed loops, let alone while loops. So I would distinguish between two types of loops: strict sequences, and "for all" loops. Neither should be reduced to the other.  
> **username_6**: Remark 2. If a for loop is syntactic sugar around a while loop, and you teach the latter first, shouldn't you argue that a while loop is syntactic sugar around a `if / goto` combination and teach that first? Or maybe I'm just kidding. I do think that showing some mechanism later because it can be reduced is the wrong approach. I try to teach the highest abstraction first.  
> **username_7**: @VictorEijkhout I tend to point out early on that all of programming is made up, but that the CPU is more of a 'given', because we have to construct a physical thing to run a nonphysical process. That is the leap which makes programming different from everything else. The interface between transistors and a program is the 5 operations a CPU can do, and it is well worthwhile to pierce the bubble of obscurity about computers right at the start. Then there is some basis for the abstraction. Variables are unlike anything else in the universe. It is a wonder to behold.  
> **username_6**: @ScottRowe I'm not exactly sure what you are arguing. Variables were not mentioned in any of the foregoing. But I think the CPU should stay out of elementary teaching. We have a language with a defined syntax and semantics, and that's our computer. Whether that's executed underneath by electrons, water power, or voodoo, is immaterial.  
> **username_4**: @VictorEijkhout WRT remark 2, putting aside for-each loops, which are ultimately a different beast, plain vanilla `for` loops are `while` loops with the advantage of everything being declared at the top, but the (corresponding) disadvantage of having the ordering be unintuitive.  If you take the sections `for(1;2;3) {4(...)}`, your looping order becomes 1 2 4 3 2 4 3 2.  By contrast, a while loop is written in execution order. `1; while(2) {3(...) 4;}` executes as 1 2 3 4 2 3 4 2.  I think this is the primary reason I've had better luck teaching `while` first, with `for` soon after.  
> **username_4**: Not to mention that the word `while` lends itself to loops in natural, everyday English in a way that `for` does not.  I think that both `for` and (eventually) `goto` can most naturally be explained from `while`, which is the most intuitive of the bunch.  
> **username_7**: @VictorEijkhout I was just responding to your statement that you like to teach the highest abstraction first. Combined with your next statement, that the CPU should be kept out of elementary teaching, you have built a bridge to the absurd. I don't understand why this is not clear to educators. We should start with the germ of the idea, just as we do with language, something children can learn with no teaching at all.  
> **username_4**: @ScottRowe We don't teach language beginning with word roots.  What are you talking about?  We start with the simplest point of entry, and then work our way *out* from there. Babies start with conversational "aaaa", then move on to phonemes, then get a few key words, and then develop vocabulary for a long time with no lower-level understanding of diphthongs, fricatives, vowels, consonants, etymologies, word roots, or the neural basis of language.  In other words, they get NONE of the "germ of the idea" for a very long time. You may try to teach it to them at the start, but good luck with that.  
> **username_4**: We are hard-wired to learn language essentially in that order.  Start with the most intuitive, at whatever level of abstraction that is, and then slowly expand your understanding.  You make these claims, but you did not start learning about computers with Turing Machines and Von Neumann architectures. Just like the rest of us, you began at the level of abstraction that best reflected whatever computer you, personally, started on, because that was what was open to you at the time.  And then you explored out from there, because that's what we all do.  
> **username_6**: @ScottRowe I'm with Ben on the levels of abstraction thing. I mostly teach C++, and there are people who approach that as "C with extras", teaching first C and the basic mechanisms, ,and then C++ and how it gives a higher level of abstraction over the C mechanisms. I completely disagree with that, and I have some very reputable people to back me up. While it's not entirely analogous, I feel that way about your notions of starting with an understanding of the CPU too. I only discuss the CPU in cases like when students get integer overflow, then I tell them about 32-bit ints.  
> **username_7**: I would think that students would like to know how computers work. Didn't you?  
> **username_4**: @ScottRowe Are you dodging on purpose?  The argument isn't about whether to cover it. The issue is about *when* to cover it.  Before a graduate school level, there are no topics that we learn from first principles, in computer science, or out of it.  That's not how the human brain works.  Not for language, not for numbers, not for song, not for writing... we don't begin at the underlying foundation.  We begin at the easiest point of entry, and then we explore out.  Computer Science is no different, because the wetware is no different.  
> **username_4**: I teach processor design and architecture.  I take my kids all the way down to the wires and the boolean gates, and they build an entire processor that way.  I don't argue against teaching low-level stuff, I think it's very important.  But it's not a class for freshmen.  I take them after they've done programming and assembly first.  
> **username_7**: Ben, I'm sorry that I keep bringing up this question and always get the same mystifying responses from most everyone. Today I was thinking that you-all are perceiving what I say from an Academic point of view. That's not what I'm saying at all. I am saying, how do you tell a kid how a computer, an electrical machine that can answer questions, can do that. Just like, what makes a car go, or, why do planes fly. Have you lost your memory of having that thought? Without some satisfying answer early on, I would have stuck with electronics, where the few books I found actually explained things.  
> **username_7**: I watched the moon landing and I watched Nixon resign. If someone wasn't direct and to the point with me when I was a child, I disregarded them and went on to get the answers myself. I guess kids now are not that way.  
> **username_4**: @ScottRowe If a total beginner asked me the question (they usually don't), I would tell them that, as crazy as it sounds, it all comes down to true and false, and, or, and not, and that if they find that intriguing, they should... then I would tell them the sequence of courses they need to arrive at processors at my school.  I've a flair for the dramatic! I like to think that I make such things sound intriguing in person. If you had been my student, I don't think you would have abandoned ship!    

---

### Answer by username_6 on 2021-12-17. Score: 3

The collatz conjecture is a great example of a while loop:

* start with any number
* if it's even, divide by 2
* if it's odd, times three and add 1
* stop if you ever reach 1. (what happens if you continue?)

The conjecture that you'll always reach 1 is just about the easiest to explain, hardest to prove, statement in math. As in: still open.

For students to explore:

* What's the longest route to 1 you can find?
* What's the biggest increase from the starting point?
* Et cetera.


---

### Answer by username_8 on 2021-12-16. Score: 2

> I struggle in finding exercises and examples which could be suitable for them.

See: [Runestone Academy](https://runestone.academy/runestone/default/user/login?_next=/runestone/default/index). Also see [CSAwesome](https://csawesome.runestone.academy/runestone/books/published/csawesome/index.html). CSAwesome is used by hundreds of teachers in the US.


---

### Answer by username_9 on 2021-12-17. Score: 2

Look at the scratch resources at NCCE.

Scratch is a graphical block based language designed for kids to learn programming.

The National Centre for Computing Education, have produced various teaching resources. As an experienced programmer, and new teacher, I used these as is the first time, then started adapting them.

<https://teachcomputing.org/curriculum/key-stage-3>

> **Comments:**
> **username_4**: I'm not based in the UK but I love teachcomputing.org.  It's such a tremendous resource!  

---

### Answer by username_7 on 2022-01-04. Score: 0

When I was teaching myself programming at age 14 I used nested For loops to make shapes on a text screen. For example, input a width and height and make a rectangle. Then modify the code to make it hollow. Then draw triangles, then diamonds.

Eventually I had a program that continuously chose shapes and sizes at random (kids love random stuff) which scrolled up the screen indefinitely. It was easy to get started and had enough challenge to be interesting.


---

