Add the 'Iteration' lesson to csintro. (#430)

This commit is contained in:
Galen Nickel 2017-06-28 01:49:20 -07:00 committed by Peli de Halleux
parent e598fc7855
commit 96815675a3
21 changed files with 498 additions and 1 deletions

View File

@ -79,6 +79,12 @@
* [Activity](/courses/csintro/conditionals/activity)
* [Project](/courses/csintro/conditionals/project)
* [Standards](/courses/csintro/conditionals/standards)
* [Iteration](/courses/csintro/iteration)
* [Overview](/courses/csintro/iteration/overview)
* [Unplugged](/courses/csintro/iteration/unplugged)
* [Activity](/courses/csintro/iteration/activity)
* [Project](/courses/csintro/iteration/project)
* [Standards](/courses/csintro/iteration/standards)
## #reference

View File

@ -35,7 +35,7 @@ UNDER CONSTRUCTION: We are still migrating the CSIntro content to this format...
2. [Algorithms](/courses/csintro/algorithms)
3. [Variables](/courses/csintro/variables)
4. [Conditionals](/courses/csintro/conditionals)
5. Iteration
5. [Iteration](/courses/csintro/iteration)
6. Review/Mini-Project
7. Coordinate Grid System
8. Booleans

View File

@ -0,0 +1,32 @@
# Iteration & Looping
This lesson introduces the concept of looping and iteration. Presents the 'While' block as a combination of an iteration and a conditional statement.
## Lesson Objectives
Students will...
* Understand the value of iteration in programming
* Understand looping as a form of iteration
* Learn how and when to use the Looping blocks repeat, while, and for
* Apply the above knowledge and skills to create a unique program that uses iteration and looping as an integral part of the program
## Lesson Structure
* Introduction: Lather. Rinse. Repeat.
* Unplugged Activity: Walk a Square pseudocode
* Micro:bit Activities: Code a Sprite to Walk a Square, Travelling Light, Micro:bit Alarm!
* Project: Get Loopy!
* Project Mods: Use servo motors to add a motion element to the project
* Assessment: Rubric
* Standards: Listed
## Lesson plan
1. [**Overview**: Iteration and looping](/courses/csintro/iteration/overview)
2. [**Unplugged**: Walk a square](/courses/csintro/iteration/unplugged)
3. [**Activity**: Loops demos](/courses/csintro/iteration/activity)
4. [**Project**: Get loopy](/courses/csintro/iteration/project)
## Related standards
[Targeted CSTA standards](/courses/csintro/iteration/standards)

View File

@ -0,0 +1,268 @@
# Activity: Loops demos
Microsoft MakeCode has three different loop blocks:
* 'Repeat' block
* 'While' block
* 'For' block
To start, the students can code the same algorithm they created in the unplugged activity using a loop.
## Repeat block
Code a Sprite to walk a square. Have students click on the Loops category in the Toolbox, and look at the three choices available.
![Loops category](/static/courses/csintro/iteration/loops-category.png)
The very first one is the repeat block! Have students drag the repeat block to the coding Workspace. Theyll notice that this block takes a **parameter**.
A **parameter** is a type of variable used as input to a function or routine. In this case, the parameter tells the repeat block how many times we want the code within the block to repeat.
For now, well leave the parameter at 4.
To create a **sprite** that will walk a square:
* Click on the Advanced category in the Toolbox. This will open up a more advanced menu of blocks.
* Click on Game category, and drag a create sprite block to the coding workspace.
![Game category](/static/courses/csintro/iteration/game-category.png)
* Well need two more blocks from the Game menu. Referring to their Walk a Square pseudocode, see if the students can find the blocks they need for moving their sprite and turning their sprite.
* Drag out a move by block and a turn right by block.
* They now have these blocks in their coding workspace.
* For this project, they can delete the default forever block.
![Game sprite blocks](/static/courses/csintro/iteration/game-sprite.png)
Time to fix those default parameter values!
* We want our sprite to start in the top left corner of the micro:bit screen, so change the parameters for both **x** and **y** to zero.
* To make the sprite move from one side of the screen to the other (as though walking around a chair), change the move by parameter to **4**.
* To make the sprite turn to walk a square, change the turn right by degrees to **90**. For now, it's OK to leave the sprite turning right instead of left as we did in our pseudocode.
Your blocks now look like this:
![Game sprite blocks params](/static/courses/csintro/iteration/sprite-params.png)
Notice that the blocks are all grayed out. Thats because we have not yet attached them to any event handlers.
* On start, we want the sprite to appear. To make this happen, go to the Variables menu and drag a set item to block to the coding window.
* Place the set item block into the on start block.
* Attach the create sprite block to the set item block
```blocks
let item: game.LedSprite = null
item = game.createSprite(0, 0)
```
You should now see the sprite appear in the top left of the micro:bit simulator.
* To add more control for when our sprite moves, drag a on button A pressed block from the Input menu.
* Place the repeat block into the on button A pressed block
* Place the move by block into the repeat block
* Place the turn right by block into the repeat block just under the move by block.
```blocks
let item: game.LedSprite = null
item = game.createSprite(0, 0)
input.onButtonPressed(Button.A, () => {
   for (let i = 0; i < 4; i++) {
       item.move(4)
       item.turn(Direction.Right, 90)
   }
})
```
Go ahead and run the program. Make the sprite move by pressing button A.
What happened? Did you see the sprite move? No?
## Slo-Mo
A helpful feature of Microsoft MakeCode is "Slo-Mo", or slow-motion mode.
* Click on the snail icon under the micro:bit simulator.
This will slow down the execution (running) of the program, and highlight parts of your code so you can see step-by-step, which line of code is being processed.
![micro:bit sim in slo-mo](/static/courses/csintro/iteration/microbit-slo-mo.png)
Now run your program several more times. Do you see the different lines of your code highlighted as the program runs? Do you see the sprite move?
![Slo-Mo in blocks](/static/courses/csintro/iteration/slo-mo-blocks.png)
Slo-Mo in Blocks
![Slo-mo-in JavaScript](/static/courses/csintro/iteration/slo-mo-javascript.png)
Slo-Mo in JavaScript
So, the code is running and the sprite is moving! Sometimes we forget just how fast computers are. So that we can see the sprite move even in regular mode, lets add a pause to our program right after each time the sprite moves. This will give our human eyes a chance to see it move.
* Click the snail icon again to turn off Slo-Mo.
* From the Basic Toolbox category, drag a pause block to the coding window and add it to our repeat block right after the turn right by block.
Your final program should look like this:
```blocks
let item: game.LedSprite = null
input.onButtonPressed(Button.A, () => {
   for (let i = 0; i < 4; i++) {
       item.move(4)
       item.turn(Direction.Right, 90)
       basic.pause(100)
   }
})
item = game.createSprite(0, 0)
```
Run your program again. Now we can see the sprite move. It still moves pretty quickly, but at least we can see it move.
If there is time, let the students experiment with changing the parameters to see how these changes affect their program.
We just used the first of the 3 different types of Loop blocks available to us. What about the other 2 loop blocks, while and for?
## For block: Traveling light
The for block is useful when you have a variable in your loop that you want to change by a fixed amount within a specific range each time through a loop. What does this mean? Lets look at an example.
Lets make an led light move across the entire display from left to right, top row to bottom row.
Our pseudocode for the first row might look like this:
```
Turn led x:0, y:0 on
Pause
Turn led x:0, y:0 off
Pause
Turn led x:1, y:0 on
Pause
Turn led x:1, y:0 off
Pause
Turn led x:2, y:0 on
Pause
Turn led x:2, y:0 off
Pause
Turn led x:3, y:0 on
Pause
Turn led x:3, y:0 off
Pause
Turn led x:4, y:0 on
Pause
Turn led x:4, y:0 off
```
Thats a lot of code, most of it repeated. Perfect for a loop.
* What is the only variable that is changing in this pseudocode? _The value of the x coordinate_.
* How much is the value of the x coordinate changing each time? _The value of the x coordinate is changing by 1 each time_.
* What is the range of values for the x coordinate? _The range of values for the x coordinate is 0 through 4_.
Now lets code!
* From the Loops Toolbox drawer, drag a for block to the coding workspace.
* Since well be changing the value of the x coordinate, make a new variable, named **xindex**.
* Well plot and unplot the leds to turn them on and off. From the Led Toolbox drawer, drag a 'plot' block and an 'unplot' block to the coding workspace.
* From the Basic Toolbox drawer, drag two pause blocks to the coding workspace.
* Place the following blocks into the for block: the plot block, a pause block, the unplot block, the second 'pause' block.
* Place the for block inside a forever block.
```block
basic.forever(() => {
   for (let index = 0; index <= 4; index++) {
       led.plot(0, 0)
       basic.pause(100)
       led.unplot(0, 0)
       basic.pause(100)
   }
})
```
Lets look at the parameters.
* Change the index in the for block to the xindex variable we made.
* Change the value of the x coordinates in the plot and unplot blocks to this same variable.
```blocks
let index = 0
basic.forever(() => {
   for (let xindex = 0; xindex <= 4; xindex++) {
       led.plot(xindex, 0)
       basic.pause(100)
       led.unplot(xindex, 0)
       basic.pause(100)
   }
})
```
We can use the default values for the rest of the parameters.
You should now see a light moving from left to right along the top row of the micro:bit simulator.
To make our pattern continue through all the leds, we can change the value of the y coordinate as well.
To do this efficiently, using the fewest lines of code, we can even put a loop inside a loop. Loops inside other loops are known as **nested loops**.
* So that we can change the value of the y coordinate, make a new variable, named **yindex**.
* Drag out another for block from the Loops Toolbox drawer.
* Place this new for block around our original for block, all within the forever block.
* Change the index in the outer for block to the yindex variable we made.
* Change the value of the y coordinates in the plot and unplot blocks to this same variable.
```blocks
let index = 0
let yindex = 0
basic.forever(() => {
   for (let yindex = 0; yindex <= 4; yindex++) {
       for (let xindex = 0; xindex <= 4; xindex++) {
           led.plot(xindex, yindex)
           basic.pause(100)
           led.unplot(xindex, yindex)
           basic.pause(100)
       }
   }
})
```
There! With only a half dozen or so lines of code, we have made our light travel through all the coordinates on the micro:bit screen.
**Check:** Make sure the students can read this code.
Here is what is happening to the values of the x & y coordinates as the program steps through each line and loop inside the forever block:
1. In the outer of the two for loops, the value of the y-coordinate is set to 0.
2. The nested inner loop then sets the value of the x-coordinate to zero.
3. The corresponding led (x:0, y:0) is plotted and then unplotted.
4. Then the value of the x-coordinate is increased by 1 and step #3 runs again with the coordinates now (x:1, y:0).
5. Then the value of the x-coordinate is increased by 1 again and step #3 runs again with the coordinates now (x:2, y:0).
6. The inner loop keeps running like this until it has completed its loop with the value of the x coordinate now 4.
7. With the inner loop complete, the program now runs the second iteration of the outer loop, increasing the value of the y-coordinate by 1, then back to the inner loop which runs 4 more times stepping through values for x from 0 through 4.
Have the students use the Slo-Mo mode to watch the program step through the loops.
* By the end of the program run, how many times has the inner loop executed? 25
* Other than knowing that there are 25 LEDs and each is lit up once, how can you figure this out?
>_The outer loop loops 5 times altogether, once for every value of the y coordinate from 0 through 4. Each time the outer loop runs, the inner loop runs 5 times, once for every value of the x coordinate from 0 through 4. 5 runs of the outer loop x 5 runs of the inner loop = 25 times the inner loop executes._
## Mods
* If there is time, let the students experiment with changing the parameters to see how these changes affect their program.
* What happens if you switch the positions of the nested loops, so the outer loop loops through the xindex values and the inner loop loops through the yindex values?
* What happens if you remove the unplot block and the pause block below it?
## While block: micro:bit alarm!
The while block is useful when you want your program to loop until a certain event happens or a different condition is met.
For example, maybe you want an alarm to sound if someone shakes your micro:bit!
In order to turn the alarm off, you press the button A. Until you press the button, the alarm should continue to sound!
You can use a 'while' block with a nested repeat block like this:
```blocks
input.onGesture(Gesture.Shake, () => {
   while (!(input.buttonIsPressed(Button.A))) {
       for (let i = 0; i < 2; i++) {
           music.playTone(262, music.beat(BeatFraction.Half))
           music.playTone(523, music.beat(BeatFraction.Half))
       }
   }
})
```
* Can you read what this code does?
* Can you write out pseudocode that describes what this code does?
Example Pseudocode:
_When someone shakes the micro:bit, while button A is not pressed, play the two tone alarm twice. Keep playing the alarm tones until the user presses the A button._
To use sound with your micro:bit, you will need to connect it to some speakers or headphones. See how to do this here: https://pxt.microbit.org/projects/hack-your-headphones

View File

@ -0,0 +1,53 @@
# Introduction
In computer programming, iteration is the repetition of a sequence of code. A loop is a form of iteration. A loop repeats code until a certain condition is met.
## Questions for the students:
* Do you use shampoo to wash your hair? _Most will say Yes_.
* Have you ever read the instructions on a bottle of shampoo? _Most will say No_.
Most of us have never read the instructions on a bottle of shampoo, because we already know how to use shampoo.
What algorithm could you write for shampooing your hair?
Example:
1. Wet hair.
2. Apply shampoo to wet hair
3. Scrub shampoo into hair
4. Rinse shampoo out of hair
If you did read the instructions on a bottle of shampoo, you may read similar instructions as the ones you just wrote with one added step at the end. That step is Repeat.
How does this one extra step affect the algorithm?
![Shampoo flowchart](/static/courses/csintro/iteration/shampoo-flowchart.png)
In computer programming, this is known as the shampoo algorithm and is an example of a loop. It is also an example of an infinite or endless loop as the algorithm keeps repeating with no condition that ends the looping.
![Iteration cartoon](/static/courses/csintro/iteration/iteration-cartoon.png)
DBwebsolutions.com
Rinse. Repeat. has even become a meme and made its way into modern song lyrics.
What other common activities involve repetitive actions? _Examples: Singing (choruses repeat), dancing, school cheers, walking and running, exercise routines..._
## Optional
Share with your students the history of Lather, Rinse, Repeat.
Lather, Rinse, Repeat: Hygiene Tip or Marketing Ploy
By Lauren Goldstein
October 11, 1999
http://archive.fortune.com/magazines/fortune/fortune_archive/1999/10/11/267035/index.htm
(FORTUNE Magazine) In Benjamin Cheever's novel The Plagiarist, a marketing executive becomes an industry legend by adding one word to shampoo bottles: REPEAT. He doubles shampoo sales overnight.
This bit of fiction reflects a small yet significant eddy of U.S. consumer angst: If we REPEAT, are we or are we not playing into the hands of some marketing scheme? It turns out that in real life there's a reason you should repeat, or at least there used to be. In the 1950s, when shampoos began to be mass-marketed, we didn't wash our hair all that often--once or twice a week, as opposed to five times a week as most of us do now. Also, we used a lot more goop in our hair. It was the age of Brylcream and antimacassars, remember. Paul Wallace, the director of hair-care research and development for Clairol, says that when cleaning agents in shampoo came up against that amount of oil and goop, "it depressed the lather." A second application was needed to get the suds that consumers expected. Lots of suds mean that hair is already clean. Maybe too clean (there's no oil to break through), but consumers like it.
FORTUNE asked Frederic Fekkai, the noted and notably expensive New York City hairdresser, what he thought about the double lather. He says, "Yesterday I put oil on my hair for a different look and went to a restaurant where the smoke was horrible. This morning I realized I had to do two shampoos."
At any rate, Wallace says advances in shampoo technology mean that only one application of, for instance, Clairol's Herbal Essences is sufficient to break through the oiliest hair. The company has stricken the use of both REPEAT and REPEAT IF DESIRED from all Clairol products. Yet a lot of brands, like Suave by Unilever and L'Oreal, still say REPEAT. Others, like Unilever's Finesse and Revlon's Flex, opt for the less imperative REPEAT IF DESIRED. Procter & Gamble uses REPEAT IF NECESSARY on Pantene.
Getting consumers to wash twice can, of course, increase sales--in ways one might not imagine. Double sudsing leads to dry hair, Fekkai points out, and that means more beauty products! "When you do two shampoos, even if you don't usually use a conditioner, you have to use a little," he says. "The conditioner becomes very important." REPEAT. FOLLOW WITH CONDITIONER. Words Cheever's marketer could have retired on.
--Lauren Goldstein
![Shampoo bottle](/static/courses/csintro/iteration/shampoo.png)
From Wikipedia (https://en.wikipedia.org/wiki/Lather,_rinse,_repeat):
Lather, rinse, repeat (sometimes wash, rinse, repeat) is an idiom roughly quoting the instructions found on many brands of shampoo. It is also used as a humorous way of pointing out that such instructions if taken literally would result in an endless loop of repeating the same steps, at least until one runs out of shampoo. It is also a sarcastic metaphor for following instructions or procedures slavishly without critical thought.

View File

@ -0,0 +1,84 @@
# Project: Get loopy!
There are many different ways to use the three types of loop blocks.
Recall the different common repetitive actions you thought of back at the beginning of this lesson.
* How will you use loops to create something useful, entertaining, or interesting?
* What might you make?
Here are some suggestions:
* Create an animated gif (looping image that changes) and add music that matches.
* Create animation that repeats for one of the melodies included in Make Code  (like Happy Birthday).
* Create different animations that run when different buttons are pressed.
* Create an alarm that includes sound and images. What will set the alarm off? What will make the alarm stop sounding?
* Use servo motors to create a creature that dances and changes its expression while a song plays.
## Example
![Hat Man](/static/courses/csintro/iteration/hatman.png)
Hat Man Project
### Hat Man Videos
[**micro:bit Hat Man**](https://youtu.be/Xvybu_T5IL8)
https://youtu.be/Xvybu_T5IL8
<br/>
[**micro:bit Hat Man - inside view**](https://youtu.be/ZfKgFQjygQQ)
https://youtu.be/ZfKgFQjygQQ
This project uses the micro:bit light sensor to display a happy face when it is sunny, and a frowning face when it is dark. The micro:bit is connected to a servo mounted on the inside of the container, and the smile and frown are attached to plastic coffee stirrers with tape and hot glue.
## Reflection
Have students write a reflection of about 150300 words, addressing the following points:
* Explain how you decided on your particular "loopy" idea. What brainstorming ideas did you come up with?
* What type of loop did you use? For, While, or Repeat
* What was something that was surprising to you about the process of creating this program?
* Describe a difficult point in the process of designing this program, and explain how you resolved it.
* What feedback did your beta testers give you? How did that help you improve your loop demo?
## Assessment
**Competency scores**: 4, 3, 2, 1
### Loops
**4 =** At least 3 different loops are implemented in a meaningful way.<br/>
**3 =** At least 2 loops are implemented in a meaningful way.<br/>
**2 =** At least 1 loop is implemented in a meaningful way.<br/>
**1 =** No variables are implemented.
### Variables (parameters)
**4 =** All variable names are unique and clearly describe what information values the variables hold<br/>
**3 =** The majority of variable names are unique and clearly describe what information values the variables hold.<br/>
**2 =** A minority of variable names are unique and clearly describe what information values the variables hold.<br/>
**1 =** None of the variable names clearly describe what information values the variables hold.
### Sound, display, and motion
**4 =** Uses sound, display, and motion in a way that is integral to the program.<br/>
**3 =** Uses a only two of the required element in a way that is integral to the program.<br/>
**2 =** Uses a only one of the required element in a way that is integral to the program.<br/>
**1 =** None of the required elements are used.
### micro:bit program
**4 =** micro:bit program:<br/>
`*` Uses loops in a way that is integral to the program<br/>
`*` Compiles and runs as intended<br/>
`*` Meaningful comments in code<br/>
**3 =** micro:bit program lacks 1 of the required elements<br/>
**2 =** micro:bit program lacks 2 of the required elements<br/>
**1 =** micro:bit program lacks 3 or more of the required elements
### Collaboration reflection
**4 =** Reflection piece includes:<br/>
`*` Brainstorming ideas<br/>
`*` Construction<br/>
`*` Programming<br/>
`*` Beta testing<br/>
**3 =** Reflection piece lacks 1 of the required elements.<br/>
**2 =** Reflection piece lacks 2 of the required elements.<br/>
**1 =** Reflection piece lacks 3 of the required elements.

View File

@ -0,0 +1,7 @@
# Standards
## CSTA K-12 Computer Science Standards
* CL.L2-05 Implement problem solutions using a programming language, including: looping behavior, conditional statements logic, expressions, variables, and functions.
* CL.L3A-03 Explain how sequence, selection, iteration, and recursion are building blocks of algorithms.

View File

@ -0,0 +1,47 @@
# Unplugged: Walk a square
## Objective
To reinforce the concept of iteration by having students act out the repeated steps of an algorithm in real life.
## Overview
Students will give the teacher instructions to do a simple activity, then look for places where using iteration could shorten their code and make it more efficient.
![Chair](/static/courses/csintro/iteration/chair.jpg)
## Process
* Place a chair in the front of the room.
* Stand at the back right side of the chair facing the students.
* Ask the students what instructions they could give you that when followed would lead you to walk around the chair, ending up just as you started. You may want to demonstrate what this would look like by walking around the chair.
* Tell the students you can only process one instruction at a time, so their algorithm needs to be step-by-step.
* As students suggest instructions write them on the board or wherever everyone can see them. Their pseudocode will probably end up looking something like this:
1. Step forward
2. Turn left
3. Step forward
4. Turn left
5. Step forward
6. Turn left
7. Step forward
8. Turn left
![Square walking pattern](/static/courses/csintro/iteration/square-walk.png)
* Go ahead and follow their algorithm to prove that it works. But thats eight lines of code! Tell students that the same instructions can be written using just three lines of code. If they have not noticed already, have students look for places where the code repeats.
* Tell them that whenever you have code that repeats, you have an opportunity to use a loop to simplify your code.
* Prompts:
>* What lines are repeated? _(1) Step forward. (2) Turn left_.
>* How many times are they repeated? Four
>* So how could we rewrite this code? Students will suggest a version of the following:
>_Repeat 4 times: Step forward, Turn left_
* Go ahead and follow their revised algorithm to prove that it works.
There! They have just rewritten eight lines of code as three lines of code, by using a loop.
The repeat command creates a loop. The code within the loop gets repeated a certain number of times until a condition is met. The condition in this algorithm is that the code in the loop is repeated 4 times. Once this condition is met, the program exits the loop.
This is a great opportunity to have the students think of the benefits of having fewer lines of code. _Some possible reasons: Less typing, saves time, fewer chances of making a mistake, easier to read the code, fewer lines of code to debug..._
## Notes
* Depending on the particular class, you can make this exercise more challenging, by requiring the students to be more specific in their instructions.
For example: Step forward 14 inches (you can have students actually measure the exact distance), turn left 90 degrees...

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 244 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB