Learn the difference between a definite loop and an indefinite loop. Examine two Scratch programs that illustrate the Scratch equivalent of a for loop in other programming languages. Learn about the concept of costumes in Scratch and how costumes can be used to animate a sprite.
Published: May 11, 2008
Last Revised: May 16, 2008
By Richard G. Baldwin
Homeschool Programming Notes # 112
This tutorial lesson is part of a continuing series that is designed specifically for teaching computer programming to homeschool students and their parents. However, even though the series is designed for homeschool students, everyone is welcome to use the lessons to learn computer programming.
In this lesson, I will begin by providing a real-world example of the difference between a definite loop and an indefinite loop.
Then I will present and explain two Scratch programs that illustrate the Scratch equivalent of a for loop in other programming languages. In Scratch, it is called a repeat. One of the programs causes a block of code to be executed a fixed number of times each time the user clicks the green flag. The other program causes a block of code to be executed a variable number of times each time the user clicks a sprite.
I will provide a brief introduction to the topic of animation. I will also explain the concept of costumes in Scratch. Both of the programs mentioned above will illustrate the use of costumes to implement crude animation that makes it appear that a cat sprite is walking.
I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.
I recommend that you also study the other lessons in my extensive collection of online programming tutorials. You will find a consolidated index at www.DickBaldwin.com.
In an earlier lesson (see Resources), I told you that any programming logic problem could be solved using an appropriate combination of only three programming structures, none of which are complicated. The three structures are known generally as:
I explained the sequence and selection structures in earlier lessons. I will concentrate on the loop structure in this lesson.
Definite versus indefinite loops
Loop structures in programming fall into two broad categories:
There are numerous sub-categories within these broad categories. I will illustrate the difference between a definite loop and an indefinite loop with two real-world examples.
A definite loop example
Assume that you are confronted with a full box of cookies. Assume also that you have more self-control than most of us, and that you decide you can eat three cookies, but no more than three, in order to keep your waistline under control. You might eat the three cookies using an algorithm something like that shown in Figure 1.
Figure 1. A definite loop for eating cookies.
for count = 1 to 3 Take cookie from box Eat cookie Increase count by one Go back to the test at the top of the loop Stop eating cookies |
Explanation of the definite loop
Being the self-controlled individual that you are, you would set your cookie limit to 3 and you would set count to 1. You would then test count to see if it is within the range from 1 to 3 inclusive. If so, you would take a cookie from the box and eat it. Then you would increase the value of count by 1 and go back to the top of the loop.
Back at the top of the loop, you would once again test the value of count to determine if it is still within the range from 1 to 3 inclusive. If so, you would repeat the process, getting and eating another cookie, increasing the value of count by 1, and going back to the top of the loop.
When you find that the value of count has advanced to 4, you would recognize that this is outside the range of 1 to 3 inclusive. As a result, you would terminate the loop and stop eating cookies. Well done!
An indefinite loop example
Assume once again that you are confronted with the same full box of cookies. However, like many of us, you aren't blessed with a lot of self-control. In that case, you might eat cookies using the algorithm shown in Figure 2.
Figure 2. An indefinite loop for eating cookies
Set the value of stillHungry to true while ((stillHungry is true) and (box is not empty)) Take cookie from box Eat cookie If I am no longer hungry Set stillHungry to false Go back to the test at the top of the loop Stop eating cookies |
Explanation of the indefinite loop
Unfortunately, for many of us, as soon as we see the full box of cookies, our stillHungry variable gets set to true.
We begin the process by performing a test to determine if stillHungry is true and the box of cookies is not empty. If that test returns true, we take a cookie from the box and eat it. Then we perform another test. If we are no longer hungry at that point, we set our stillHungry variable to false and go back to test at the top of the loop. Otherwise, we allow our stillHungry variable to remain true.
Back at the top of the loop, we test again to determine if stillHungry is true, and the box of cookies is not empty. If the test returns true, we go through the process again, eating another cookie, etc.
Eventually, either our stillHungry variable will be set to false, or the cookie box will become empty. At that point, the test will return false. We will terminate the loop and will stop eating cookies even though we might still be hungry for more cookies.
The while and for keywords
Most modern programming languages use the keywords while and for to implement loop structures such as this and we will see those keywords in use once we get to Java. However, Scratch does not use those keywords to implement loops. Regardless, when I present pseudocode examples to explain Scratch programs, I will continue to use while and for to get you accustomed to that terminology.
In this lesson, I will present and explain the following two Scratch programs:
In addition, I will provide the specifications for a student-programming project for you to demonstrate your understanding of what you learned from the two programs listed above. In addition, this programming project will require you to do some independent research into the manner in which Scratch sprites can communicate with one another.
This program illustrates the Scratch equivalent of a for loop in other programming languages. In Scratch, it is called a repeat.
The program places a cat sprite having two costumes on the screen. When the
user clicks the green flag, code is executed that is equivalent to the
pseudocode shown in Figure 3.
Figure 3. Pseudocode for the program named ForLoop01.
Initialize cat position, orientation, and costume for(count = 0;count < 24,count = count + 1){ Cat moves ten steps forward. Cat waits 0.1 second Cat switches to costume #2 Cat turns 15 degrees Cat waits 0.1 second Cat switches back to costume #1 }//end for loop |
Why set count to 0?
Most modern programming languages typically start counting with 0 instead of 1, but that is not necessarily the case with Scratch. I will have a lot more to say about this topic when we get into Alice and Java.
Purpose of the pseudocode
My purpose in providing the pseudocode is to help you better understand the Scratch code that follows. I am also preparing you for the use of Java later. I recommend that you compare the pseudocode with the Scratch code, and compare both of them with what you see when you run the program.
What's new in this Scratch program?
This program contains several new commands that haven't been used in previous lessons:
The only one of these commands that I would put in the programming fundamentals category is the repeat command, and even the syntax of that command is quite a bit different from other modern programming languages. However, the other commands are some of the things that cause Scratch programming to be fun, so I will use and explain such commands as we go along. My only caution is that you should not expect to find those commands in other programming languages, at least not using the same syntax.
Animation
Since the earliest days of animation (See KidZonline 2D Animation videos in Resources), two-dimensional (2D) animation has been created by presenting a series of drawings to the viewer in rapid succession where each drawing was similar to but slightly different from the previous drawing. Because of the property of human vision to blur one image into the next, if the images are sufficiently similar and they are presented in rapid succession, the human mind perceives the series of images as continuous motion. This is how motion pictures work, and it is also how the cartoons that you see on television work.
Costumes
Animation can be created in a couple of different ways in Scratch. One way is through the use of something called costumes. For example, when you start a new project in Scratch, an image of a cat having two costumes is automatically added to the project. Figure 4 shows a screen shot of the center panel in the user interface for a new project with the Costumes tab selected.
Figure 4. The costumes tab for a new Scratch project.
The cat sprite has two costumes
As you can see, the cat sprite has two costumes, which are really two different images of the cat. The images are designed to make it look like the cat is walking if the two images are repeated in rapid succession. You can also see that each costume has a name, with the default names in this case being:
If you choose to do so, you can click in the boxes containing the names and modify them. Also, if you choose to do so, you can click the Edit button for a costume. This will bring up a drawing program that you can use to modify the drawing. However, most of that is beyond the scope of this lesson so we won't get into it here.
Loop blocks
If you click the tan Control button in the Scratch user interface (see Figure 5), you will expose a large number of blocks that are generally used to control the flow of the program. The following control blocks that are exposed by that button can be used to construct loops:
The repeat (numeric value) block
The repeat (numeric value) block (referred to hereafter simply as the repeat block) provides the mechanism by which you can cause a set of actions to be executed a specified number of times. You create a repeat block that will do something useful by inserting programming statements into the opening in a raw repeat block. When you drag a raw repeat block into the center panel, it looks like the tan image in Figure 5.
Figure 5. Various Scratch blocks.
Setting the number of repeats (iterations)
By default, the white box in the repeat block contains a literal numeric value. You can modify that value and specify the number of times that the code in the repeat block will be executed. When you use a literal value, the code will be executed the same number of times every time you run the program.
Can also use a variable
Note that I also created a dummy variable in Figure 5 for illustration purposes. Because the shape of a variable block is the same as the shape of the white box in the repeat block, you can also drop a variable block into the box. When you do this, the value of the variable will be used to determine how many times the code in the block will be executed. That number may be different each time the repeat block is executed.
The wait command
Figure 5 also shows a wait block, which can be dragged into the center panel from the tan group of Control blocks. Like the repeat block, the wait block has a white box into which you can either enter a literal value or drop a variable block.
The program will pause for a specified number of seconds (which may be a decimal fraction) each time the wait command is executed. If you enter a literal value into the box, the program will pause for the same amount of time each time the wait command is executed. If you drop a variable block into the box, the length of the pause will be the current value stored in the variable, which may be different each time the command is executed.
The switch costume command
Finally, Figure 5 shows a purple switch to costume block. This block is available when any of the sprites appears at the top of the center column in the user interface. However, when the Stage appears at the top of the column, the block changes to one labeled switch to background. (A discussion of backgrounds will be deferred to a future lesson.)
As you can see, the switch to costume block has a pull-down list that allows you to select a specific costume for the command when you write the program. The list contains all of the costumes belonging to the particular sprite that appears at the top of the column. In the case of the default cat that appears for new projects, there are two costumes in the pull-down list because the cat has two costumes as shown in Figure 4.
The program code
The code for this program is shown in Figure 6.
Figure 6. Program code for the program named ForLoop01.
Behavior of the program
The program loads with the cat somewhere on the Stage as shown in Figure 7. When the user clicks the green flag, the cat moves to the center of the stage (the origin of the Cartesian coordinate system) and turns to face the viewer's right. In addition, the cat switches to costume1 (see Figure 4) even if that isn't necessary at this point. (Except for switching costumes, you have seen code like this in earlier lessons.)
Figure 7. The cat on the Stage.
The repeat block
Then the code inside the repeat block shown in Figure 6 is executed 24 times in succession.
During each execution (iteration) of the repeat block, the cat:
This causes the cat to appear to walk (in a rather jerky fashion) in a circle, ending up very close to where it began.
Run the online version
In order to get the full impact of this program, you will either need to create the program yourself or run the online version (see Resources).
This program is an upgrade of the program named ForLoop01. The behavior of this program is the same as the earlier program with the following exceptions:
Figure 8. Program ForLoop02 output after clicking the green flag.
Figure 9. Program ForLoop02 output after clicking the cat.
The program code
The code for this program is shown in Figure 10.
Figure 10. Program code for the program named ForLoop02.
Create a variable
The code in the left panel in Figure 10 creates a variable named numberLoops and causes it to be displayed on the Stage as shown in Figure 9. (It was necessary to right click on the displayed version of the variable to cause the slider to be exposed during the writing of the program.)
The initialization code
Although there is quite a lot of code that is executed when the green flag is clicked, there is nothing new there. All of that code has been explained in this or earlier lessons.
The repeat block
The only thing that is really new to this program is the use of the variable block named numberLoops to specify the number of times that the code in the repeat block will be executed each time the cat is clicked. Otherwise the code in the repeat block in Figure 10 is the same as the code in the repeat block shown in Figure 6.
The operational difference
The operational difference is that each time the repeat block in Figure 6 is executed, the code inside the repeat block will be executed 24 times. Each time the repeat block in Figure 10 is executed, the number of times that the code inside the repeat block will be executed is specified by the current position of the slider in Figure 9. This, in effect converts the static program named ForLoop01 into an interactive program in which the user has some control over the program behavior at runtime.
Online versions of these programs are available
Copies of these two programs have been posted online for your review (see Resources for the URL). If you don't find the programs using that URL, search the Scratch site for the user named dbal.
I encourage you to use the information provided above to write and run these two programs. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.
Just for fun, see if you can add a drumbeat that keeps time as the cat walks.
I also encourage you to write the program described below.
Write a Scratch program named ForLoop03. This program places a cat sprite, a slider variable, and a button on the stage as shown in Figure 11. The cat sprite has two costumes.
Figure 11. ForLoop03 output after clicking the green flag.
This program is an upgrade of the program named ForLoop02, but is more complex than that program. In particular, this program uses the ability of one sprite (the button) to communicate with another sprite (the cat) by broadcasting and receiving messages
When the user clicks the button, this program behaves just like the program named ForLoop02 behaves when the user clicks the cat in that program. (Note, however, that the drawing of axes and lines was omitted from this program for simplicity.)
As in the previous program, this program executes its animation using a repeat block. Also as in the previous program, the number of times that the code in the repeat block is executed is specified by the current position of the slider.
Online version is available
A copy of this program has been posted online for your review (see Resources for the URL). If you don't find the program using that URL, search the Scratch site for the user named dbal.
I began by providing a real-world example of the difference between a definite loop and an indefinite loop.
Then I presented and explained two Scratch programs that illustrate the Scratch equivalent of a for loop in other programming languages. In Scratch, it is called a repeat. One of the programs caused a block of code to be executed a fixed number of times each time the user clicked the green flag. The other program caused a block of code to be executed a variable number of times each time the user clicked a sprite.
I provided a brief introduction to the topic of animation and I explained the concept of costumes in Scratch. Both programs illustrate the use of costumes to implement crude animation that makes it appear that a cat sprite is walking.
The next lesson will concentrate on other variations of Scratch loops.
Copyright 2008, Richard G. Baldwin. Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.
In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP). His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments. (TI is still a world leader in DSP.) In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
-end-