BFOIT

  Introduction to Programming  

Iteration and Animation


*Note*    In 2007, these lessons were significantly modified.    *Note*
This is a link to the new materials.
This is a link to the new iteration and animation lesson.


Introduction

We worked our way through defining procedures in the last lesson so that our programs could be built in small, understandable pieces.  The smaller your programs are, the less you type, and the better chance your program will do what you want it to do.  In this lesson, you are going to learn about another powerful mechanism for writing smaller programs: iteration.

As you write more and more Logo programs, you will notice that to do certain things your code repeats similar patterns.  Programming involves recognizing these patterns.  There are a few ways to reduce the number of duplicate instructions your programs contain.  Iteration is one which we cover in this lesson.

We'll end the lesson with an introduction to animation.  Animation is everywhere in the digital world.  On the index page for these lessons there is a Java applet that draws a maze and then solves it.  It shows off the solution via animation.  In this lesson you will learn how to perform simple animation.


Drawing a Circle, Step by Step, One Point at a Time

You might think that drawing a circle requires knowing geometry or trigonometry - subjects which you may not have had in school yet.  Don't worry if you haven't mastered these subjects, that's not going to stop you from getting the turtle to draw a circle in this lesson.  We'll figure out how to do it the same way we solve many programming puzzles - we'll start by working with things we know how to do.

Here are a couple of definitions of a circle:

A closed plane curve every point of which is equidistant from a fixed point within the curve (Webster's New Collegiate Dictionary).

A circle is the set of all points in a plane at a fixed distance from a fixed point in the plane (www.math.psu.edu).

Let's look at some pseudo code that instructs the turtle to draw a bunch of points that are all the same distance from the center of the GraphicsCanvas. 

Here is pseudo code from an experienced programmer.

   1. pick up the pen so it's not leaving a trace
   2. move some number of steps forward, for example: 100
   3. put the pen down so it will draw
   4. move a few steps forward to make a little mark
   5. pick up the pen so it's not leaving a trace
   6. return to the center
   7. turn a bit to the right
   8. repeat steps 2 through 7 until the turtle is back to
      its original heading - it has rotated 360 degrees
  

Ok, it's up to you to convert this pseudo code to Logo instructions and type them in, see if they work. 

Here is the TG applet for you to use.

alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag!
TurtleGraphics Applet

Tip: The left mouse buttom can be used to change the heights of the GraphicsCanvas and the CommandCenter.  Hold the left mouse button down while on the name stripe between these subwindows and drag it up/down.

Tip: When you press the up-arrow key while you are working in the CommandCenter, it brings up the previous line of input.  Press it again and you will get the line before this.  This continues until some maximum number of saved lines is reached.  Once you've nailed down the code that draws a point and rotates the turtle, you can put all of these instructions on a single line and repeat it using the up-arrow.

Tip: The best solution (my opinion) is to write a new procedure which draws one point, then invoke it a bunch of times.  This procedure will be complex enough for you to use TG's editor.  Open it with the Window->Editor->Open menu item.  Give yourself more editing space when you are entering the instructions, less when you want to see the full results in the graphics area.

I think what you will find is that it works, but it is going to take a lot of typing.  A LOT of typing.  Too much typing.

If you decided to to take the procedural abstraction approach you learned in the last lesson, you had to do a lot less typing.  Here's how I approached the exercise, showing what I mean.

   to pointOut100
     penup forward 90 pendown forward 20
     penup back 110
     end

   to main
     setpensize 20
     pointOut100 right 10
     pointOut100 right 10
     ...repeated 36 times...
     end
There is one command in this source code that you haven't seen (unless you've visited Appendix B) - the setpensize command.  It takes an integer as an input and sets the width of the line drawn by the pen to be this number of steps.  By setting the width of the pen to 20 steps and using it to draw a line 20 steps long, i get a big box, or... a big point!

But, there are often many ways to write a program to do something.


Walking in a Circle

Back in the Introductory Logo Commands lesson, I gave you the source code that drew a box.  Then, it was your turn to explore putting together the code to draw a triangle, a pentagon, a hexagon and an octagon.

What does all of this have to do with drawing a circle?  Well, think about it... the more sides you added to your figures, the more closely they resemble a circle.  Watch for yourself.

My guess is that by the time you get up to 24 or 36 sides, we'll have a pretty good circle. 

Here are lists of Logo instructions that draw a triangle, a square, and a pentagon:

Triangle Square Pentagon
forward 100 forward 90 forward 80
right 120 right 90 right 72
forward 100 forward 90 forward 80
right 120 right 90 right 72
forward 100 forward 90 forward 80
right 120 right 90 right 72
  forward 90 forward 80
right 90 right 72
  forward 80
right 72
Table 5.1

Look how much is common to these three lists of instructions.  As I mentioned in the introduction, you need to discover patterns that appear in the programming process.

  1. the number of forward commands used to draw each of the figures is equal to the number of sides in the figure,
  2. the number of right commands used to draw each of the figures is equal to the number of corners in each figure,
  3. the number of steps we tell the turtle to move in every forward command for each figure are the same amounts (example: for the triangle, every forward command specifies 100 turtle steps),
  4. the number of degrees we tell the turtle to rotate in every right command for each figure are the same amounts (example: for the square, every right command specifies 90 degrees),

The only three things that are different in the lists are:

  1. the distance we tell the turtle to move,
  2. the number of degrees we turn the turtle between the forward commands, and
  3. the two extra commands (forward and right) it took to draw the square, and the four extra commands (again, forward and right) it took to draw the pentagon.

Either go back up to the TG applet or click here to start up a separate page with the applet on it.  Use one of these to type in procedures for the code in Table 5.1, i.e., define procedures tri100, sqr90, and pent80.  Invoke them to make sure they do what you think they should do.  Then, answer the following questions:

What happens if you change the number of turtle steps
specified on the forward commands?


What happens if you change the number of degrees
specified on the right commands?


What rules must be followed in order for the turtle
to end up just like it started, i.e., at the same
initial point on 
the GraphicsCanvas, pointing in the same direction
as when it started?


Summary of Drawing a Circle

By now, you've completed the first phase in working through drawing a circle: Understanding the problem.  Now it is up to you to devise a plan you'll use to write a procedure that instructs the turtle to draw a circle.  You should now know two ways to get the turtle to draw a circle in the Logo language.  The problem is that both approaches take a LOT of typing.

The first way we approached the problem requires drawing points some distance from the center of the circle.  If you refer back to the pseudo code for this approach, you will see that if we draw one point for each degree in a circle, it will take 2,161 instructions (assuming each step of pseudo code translates into a single instruction).  If you define a procedure that performs steps 2 - 7, you can reduce your program to 370 instructions.  By defining procedures that contain other procedures you can reduce the total number of instructions.

But, there's got to be a better way...

For our other approach (where we have the turtle repeating a sequence of walking a bit forward and then turning a little bit), a regular polygon with 36 sides will take 72 instructions.  This is less typing, but still too much...

There is a better way to reduce the number of instructions needed; it's called iteration.

Let's learn about it now - interation to the rescue!


Iteration, aka Repeating Something

In the Summary in the "Introductory Logo Commands" lesson, I emphasized that the sequence that the steps in our programs get done in is extremely important.  In the TG applet (or TG application), when you are working in the CommandCenter, instructions (the steps in your program) are executed left to right on each line after you press the [Enter] key.

Well, Logo has a way for you to tell its interpreter to execute of a list of instructions a number of times.  The syntax of the Logo repeat command is:

   repeat       <number>       <List-of-Instructions>   

  1. the command name: "repeat"
  2. a <number>, and
  3. a <List-of-Instructions>

And, the syntax of a <List-of-Instructions> is:

   [       <Instructions>       ]   

  1. an open square bracket,
  2. <Instructions>, and
  3. a close square bracket

For example, here are repeat instructions which draw a triangle and a box:

   repeat       3       [       forward 100 right 120       ]   
   repeat       4       [       forward 90 right 90       ]   


Logo Animation - Watching Iteration

Here is a small program which draws a circle the way I first described.  It draws a bunch of fat points equally distant from the center.  Watch how the program gets executed, step by step.  Especially watch how repeat's count gets decremented after each time its List-of-Instructions is executed.

alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag!


Animation - Moving an Object Across the GraphicsCanvas

Either go back up to the TG applet or use either a small popup TG applet to try out the following instructions.
    hideturtle setpensize 10 setc 4
    repeat 15 [ fd 10 wait 500 setc 7 bk 10 fd 10 setc 4 ]
    repeat 15 [ bk 10 wait 500 setc 7 fd 10 bk 10 setc 4 ]
So, moving a 10x10 turtle-step box up/down the screen is just iteration of the steps:
  1. draw something,
  2. pause for some amount of time,
  3. erase what was drawn,

  4. move a bit, and go back to step 1.


Exercise: JumpinJack

Ok.  Figure 5.1 shows three different positions of a stick figure performing jumping jack exercises.

#1 #2 #3
Figure 5.1

Here is the source code for JumpinJack #1.  It's up to you to write procedures: arms2, arms3, legs2, legs3, fig2, fig3 and then modify main such that it iterates through the three figures to animate Jack, or is it Jill???

    to arms1
      setpensize 8
      forward 25
      right 45 forward 50 back 50
      left 90 forward 50 back 50
      right 45
      back 25
      end

    to body
      setpensize 16
      forward 60 back 80 forward 20
      end

    to head
      penup forward 45 pendown
      setpensize 10
      repeat 12 [forward 16 back 16 left 30]
      back 45
      end

    to legs1
      setpensize 8
      back 15
      right 135 forward 60 back 60
      right 90 forward 60 back 60
      left 225
      forward 15
      end

    to fig1
      head
      body
      arms1
      legs1
      end

    to main
      home hideturtle clean setheading 0
      fig1
      end

    main


Additional Exercises

  1. Write a program which draws a circle as a regular polygon with enough sides for it to appear to be a circle.  This is the second way I described how a circle can be drawn.
  2. Take a look at the arc in the following figure.  This particular arc is one quarter of a circle.  Now take a close look at the plant with a flower.  You've learned how to draw a circle in this lesson.  Now write a bunch of procedures which instruct the turtle to draw a plant that looks like the one in Figure 5.2b.

    a. Arc b. Plant With Flower
    Figure 5.2

  3. A solid-colored box can be drawn as a bunch of parallel lines.  Draw a box that is 100 turtle steps on each side and filled in a solid red color.  Figure 5.3 shows the desired results.

    Figure 5.3 (Solid-red Box - 100 TurtleSteps on a Side)

  4. Write a bunch of procedures which draw a brick wall.  Like the previous exercise, the heart of your program will be two procedures which draw a brick and a half-brick.  These should be used in two procedures, one draws a line of whole bricks and the other draws a line starting and ending with a half brick.  Put it all together with a main procedure.  See Figure 5.4 for an example of the expected drawing.
  5. Figure 5.4 (Brick Wall)


Summary

Iteration - repeating something a some number of times - is a powerful way to reduce the size of a computer program.  The something may not be obvious when you start writing a program; it can be a pattern you recognize when you are typing in your programs.  So, look closely for patterns in the code you write.  As you get more and more experience writing programs, you'll start to think about iteration as a basic building block of programming.

Drawing a circle as a 72-sided regular polygon takes 144 instructions without taking advantage of iteration.  But, making 2 instructions part of a single repeat command achieves the same results!


New Logo Primitive Procedures Used In This Lesson
Name Input(s) Description Example
REPEAT count
instructionList
The instructionList input is performed the number of times specified by the count input. REPEAT 4 [ FD 100 RT 90 ]
SETPENSIZE
SETPS
number Sets the width of the turtle's pen, which determines the thickness of the trace it leaves, the line it draws. SETPS 5
WAIT number Performing instructions is suspended for the number of milliseconds (1/1000s of a second). WAIT 1000


Back to Table of Contents
Back to previous Lesson ( Defining Your Own Commands )
On to next Lesson ( Procedure Inputs )