Elementary Programming Concepts

Looping - Repetition

To reduce the number of expressions given to a robot we use loops.

Loops allow you to repeat a sequence of expressions.

A script to create a six pointed star without loops

| pica |

pica := Bot new.

pica go : 70.

pica turnLeft: 180.

pica go : 70.

pica turnLeft: 180.

pica turnLeft: 60.

pica go : 70.

pica turnLeft: 180.

pica go : 70.

pica turnLeft: 180.

pica turnLeft: 60.

pica go : 70.

pica turnLeft: 180.As you can see, after pica is created it repeats the same 5 lines of

pica go : 70.code.

pica turnLeft: 180.

pica turnLeft: 60.

pica go : 70.

pica turnLeft: 180.

pica go : 70.

pica turnLeft: 180.

pica turnLeft: 60.

pica go : 70.

pica turnLeft: 180.

pica go : 70.

pica turnLeft: 180.

pica turnLeft: 60.

pica go : 70.

pica turnLeft: 180.

pica go : 70.

pica turnLeft: 180.

pica turnLeft: 60.

The more efficient way of writing this is to use loops. There are different kinds of loops but the one introduced in this chapter allows you to repeat a given sequence of messages a specified number of times.

The method

timesRepeat:

repeats a sequence of expressions a given number of times.

A script for the same 6 branched star as above using the timesRepeat loop:

| pica |

pica := Bot new.

6 timesRepeat:

[ pica go: 70.

pica turnLeft: 180.

pica go: 70.

pica turnLeft: 180.

pica turnLeft: 60 ]

Syntax:

ntimesRepeat: [sequence of expressions]

The sequence of expressions is delimited by square brackets [….] and is known as a block.

The message timesRepeat: is sent to an integer (n), the number of times the sequence should be repeated.

The number receiving the message must be a whole number.

The argument of timesRepeat: is a block, that is, a sequence of expressions surrounded by square brackets.

Exercise

Write a script to draw a star with 60 branches.

Code Indentation

Code can be laid out in a variety of ways and its indentation from the margin as in the example above has no effect on the how the code is executed. i.e. indentation has no effect on the syntactic “sense” of the program. However using clear and consistent indentation helps the reader/editor to understand the code.

The indentation used in the 6 branched star above shows the concept of the repeated block of expressions delimited by the square brackets [..] forming a visual and textual rectangle.

Drawing Regular Geometric Figures

Exercise 2

Using timesRepeat:

i)Write a script drawing a square

ii)Write a script drawing a regular pentagon

iii)Write a script drawing a regular hexagon

iv)Write a script drawing a double 5 sided pyramid as drawn earlier

v)Write a script drawing a double 10 sided pyramid

Continue with the exercises on the following two pages.

Further experiments with loops

As you have seen, generating shapes involves a repetition of code that draws two lines segments. Once you have identified the correct repeating element, you can create complex pictures from simple drawing through repetition. Use this principle to do the following experiments.

A Swiss Cross

Draw the outline of the Swiss Cross using turnLeft: or turnRight: and timesRepeat:

A Staircase

Draw the staircase below

A Staircase without Risers

Draw the stylised staircase – with treads but without risers - shown below

A Staple

Draw the graphical element that looks like a staple

A Comb

Transform the staple into the comb shown below using timesRepeat:

A ladder

Again using the staple, create the ladder graphic below

Tumbling Square

Define a loop using timesRepeat: to draw the tumbling squares below.

10 Step Pyramid

Write script to draw the 10 step pyramid below

A Growing Star

Write one script to draw the series of graphics below

Introduction to Variables

Variables are placeholders for objects and simplify the writing of programs. As the complexity of programs increases, it becomes necessary to express dependencies between variables.

Exercise

Write a script to create the shape

height 100 pixels

width 70 pixels

midheight 60 pixels

To change the height to 200, width to 100, and midheight to 70 you must change the numbers representing height, width and midheight everywhere they occur and in the correct order.

It is easy to make mistakes and is a tiresome process. To avoid this we do the following;

Declare the variables – height, width and midheight

Refer to the values as needed

Change the values if necessary

Definitions

A variable is a name with which we associate a value

  1. Declare the variable
  2. Associate a value with it – known as assigning a value to the variable
  3. Refer to the variable and obtain its value

It is also possible to modify the value associated with a variable and associate a new value with it.

i) Declaring the variables

| height width midHeight |

The variable names are enclosed within pipes (vertical lines).Pipes declare temporary variables existing only during the execution of the script.

ii) Assigning a value

height := 100.

width := 70.

midHeight := 60

The symbol := assigns a value. Assigning can involve an expression e.g. length := 120 + 30.

iii) Referring to the variable

| pica height |

pica := Bot new.In general – a variable must be declared and initialised before being used

height := 100.

pica north.

pica go: height.

pica is a variable, whose value is a robot.

Using Variables

Expressing relationships between variables

| pica height width midHeight |“declaring variables”

pica := Bot new.

height := 100.

width := 70.“initialising variables”

midHeight :=60.

pica north.

pica go: height.

pica east.“using the variables”

pica go: width.

pica south.

pica go: height.

pica west.

pica go: width.

pica north.

pica go: midheight.

pica east.

pica go: width.

All you need to do is to change the values associated with the variables once to effect major changes on your shape. Try it.

The Power of Variables

Variables can hold a wide variety of types of values. Generally to now all you have done is assigned robots or numbers to variables. However you can assign other values such as colours e.g. robotColor := Color yellow or a sound etc.

Variables make scripts more readable and easier to understand.

Expressing Relationships between Variables

The value of a variable does not need to be a simple number but can be the result of a complex computation.

A first look at relationships:

| pica height width midHeight |

pica := Bot new.The relationships here are expressed not between thevariables themselves

height := 120.but in terms of the value 120. This requires the value to be changed

width := 120 * 2 / 3.manually if we wish to change the shape

midHeight := 120 * 3 / 5.

. . . .

Developing this:

| pica height width midHeight |

pica := Bot new.

height := 120.The variables width and midheight depend on height

width := height * 2 / 3.

midHeight := height * 3 / 5.

. . . .

Initialise before using!

The only constraint you have to consider when expressing relationships between variables is that the variable used in the definition of another variable must have a value.

Problem example leading to an error

| pica height width midheight |

pica := Bot new.

width := height * 2 / 3.height is used before being initialised with a resulting error

height := 120.height is initialised here after attempting to be used

midheight := height * 3 / 5.

Experiments with Variables

Exercises

1. Scripts that Don't Work

Explain why neither of the following scripts is able to draw a letter A of height 120 pixels.

| pica height | / | pica height |
pica := Bot new. / pica := Bot new.
height := 120. / pica north.
pica north. / pica go : height
pica go: 100. / pica east.
pica east. / pica go: 70.
pica go: 70. / pica south.
pica south. / pica go: height
pica go: 100. / pica west.
pica west. / pica jump:70.
pica jump: 70. / pica north.
pica north. / pica jump: 50.
Pica jump: 50. / pica east.
pica east. / pica go: 70.
pica go: 70

2. Write a script using a variable terraceNumberto represent a pyramid below with a variable number of terraces. Base your script on your previous script using timesRepeat: .

3. Modify the script above to add a variable terraceSize to represent a pyramid with a variable terrace size.

Automated Polygons using Variables

Variables greatly simplify the definition of scripts in which some of the variables depend on other variables. The use of variables also provides great leverage in dealing with loops.

A regular pentagonA regular hexagon

| pica || pica |

pica := Bot new. pica := Bot new.

5 timesRepeat:6 timesRepeat:

[ pica go: 100.[ pica go: 100.

pica turnLeft: 72 ]pica turnLeft: 60 ]

In order to change the first script into the second you have to change the number of sides (we’ll call it s) plus the magnitude of the turn (we’ll call it T) such that the product s * T = 360.

Exercise

Using two new variables; sides (no of sides) and angle (360 / no of sides), write a script to draw any regular hexagon.

If you execute your new script above with a large number of sides, the resulting figure does not fit on the screen.

Exercise

Modify your script above using a new variable totalLength which is set to a fixed length, and let each side of your polygon have length equal to totalLength divided by the number of sides.

Naming Variables

It is important to give your variables meaningful names. The name of a variable can be any sequence of alphanumeric characters beginning with a lowercase letter. Remember two word names have the second word starting with an upper case letter e.g. totalLength.

We use long variable names that clearly indicate the function of the variable in your program. Do not x,y,z etc. This enables other programmers to understand your scripts more easily.

Being able to understand what a program does from a reading is very important.

Variables as Boxes:

Variables are placeholders that refer to objects.

Assignment: The Right and Left Part of :=

There are two very different ways a variable name is used in a script

The name used refers to its value e.g. walkLength + 100 or pica go: 100

The name is used to refer to the placeholder itself in order to initialise it or change its value

When the variable name is on the left hand side of the assignment expression :=

The value is changed (written) to the value of the expression on the right hand side of the assignment expression

Otherwise:

The variable name refers to the value associated with the variable ie. it is simply read, but not changed

e.g. the variablewalkLength is written in line 3 and then read in line 4

  1. | walkLength pica |
  2. pica := Bot new.
  3. walkLength := 100.
  4. walkLength + 150
  5. pica go: walkLength

In line 3 the variable name appears to the left of the :=. So it refers to the placeholder and the value 100 is assigned (written).

After line 3 has been executed, the variable walkLength refers to the number 100.

In line 4 walkLength + 150 is not part of an assignment expression (no := ), and so the variable name refers to the variable’s value (is read). In this particular script this line does nothing.

In line 5, both variables pica and walkLength are used to refer to their values, that is to the objects to which they refer.

walkLength + 150 returns 150 added to the value of the variable walkLength, but does not change the value of the variable.

Loops and variables

Variables and loops are commonly used in combination.

The staircase again

Exercises

Script 1

Write a script to produce the staircase shown below. All the risers have the same height but the treads get longer by a common value as you climb the staircase.

Hint:- Start with a normal staircase and modify it!

Problems that you will have encountered are that each tread needs to be calculated manually and then you are repeating an almost identical sequence of messages over and over.

Variables can be used to automate the increasing tread length and lops can be used to reduce the amount of coding.

Script 2

Change your normal staircase script to use a loop using timesRepeat: for 10 steps of the staircase

Script 3

Modify your script further to include the variable treadLength with a value of 10 pixels

Script 4

Modify your last script to increase the tread length by 10 pixels each time the loop is executed.

Looking closely at your script:

The first expression draws a treadLength the size of the value of the variable treadLength

i.e. 10 as initialised for the first time through the loop

The second expression; the robot turns and draw a riser and turns again

The third expression; the value of the tread length is increased by 10 and the loop restarts

However the value of the variable is a new, larger value.

Without the expression treadlength:= treadLength + 10, the value of the variable would never change.

This increase is known as an increment.

Experiment (Placement of the Increment in the Loop)

Try changing the last line of loop, for example, treadLength := treadLength + 15. Then try moving the line to different places in the loop. Can you explain what happens when you move the last line of the loop to the beginning of the loop?

Practice with Loops and Variables:

Mazes, Spirals, and More

Experiment (Another Bizarre Staircase)

Let's see how combining variables and loops can help you to solve some other problems.

Modify your staircase script to produce the picture shown below, which represents a staircase in which both the treads and the risers grow in size.

Experiment (A Simple Maze)

Write a script that reproduces the drawing shown below.

A Spiral

Write a script that changes the angle through which the robot turns..

Russian Squares

Draw the nested squares of different sizes as shown in the figure below. You might begin by defining a loop that draws the same square ten times. Then introduce a variable to represent the side length of a square, and finally, make the side length grow each time through your loop. As an additional challenge, you might try to write a new script that draws the same figure without the robot having either to jump or draw any line twice.

A Long Corridor

The concentric squares of different sizes shown below represent a long corridor, which seems to get smaller as you look into the distance. Start by drawing a square, and draw it starting from the centre, so when you change the square's size, the next square will automatically be drawn concentric to the first one. Define your square inside a loop, and then introduce a variable sideLength representing the side length of the square. Finally, make the square grow each time through the loop'

Important tips for Using Variables and Loops

Generally, the order of the construct is

  1. Variable is declared
  2. Variable is initialised
  3. Inside the loop, the variable is used to perform some computation
  4. Variable value is changed for the next pass trough the loop.

An outline script showing the use of variables in a loop

| treadLength pica |“variable declaration”

……

treadLength := 10.“initialisation of the variable”

……

10 timesRepeat:

[ pica go: treadLength.“variable use”

…….

treadLength := treadLength + 10. ]“variable change of value”

In Summary

  • When introducing a variable inside a loop, be careful how you initialise the variable
  • Keep in mind that a variable must be initialised before the value is used
  • Normally the initialisation occurs outside the loop, otherwise the variable would not change when the loop is repeated
  • The last value that a variable is assigned in a loop body will be the variable’s value the next time the loop is executed.

Advanced Experiments

Squares

Define a script that creates the checkerboard pattern below. This is a little more complicated than the earlier experiment, in that it is difficult to see how to draw the figure using a single loop. There are several ways of solving the problem using 2 loops. Hint: use lines rather than squares

Pyramid

Write a script that creates the construction below, representing the blocks of stones forming part of the pyramid of Saqqara. You could modify your script from above by changing the variable for the length of the lines each time through the loop.