4 Variables

Sometimes, we may want to draw shapes that are not exactly predetermined. For example, we may want to draw squares, pentagons and other shapes. Of course, knowing how to draw a triangle, we only need to tweak the steps to draw other shapes.

But that’s tedious.

Another way to solve this problem is to write the logic to draw an N-sided polygon using some rules. Assuming that we want all sides of the polygon to have the same length, we just have to change the right turn angle and the number of times to perform the steps.

We can use the word repeat to perform a sequence of actions some number of times. For example, to draw a triangle, we could use the following code:

repeat 3 [forward 200 right 120] 

Type this commend on the command bar, and you can see the shape drawn.

This is cool! However, to change this code to draw a pentagon or a square, both the loop count (3) and the turn angle (120) needs to be changed.

We can use a variable n to indicate the number of sides. Let us store this method as follows (use the editor to type this). You can append to the drawtriangle code that we edited earlier:

to drawpolygon :n  
  repeat :n [forward 200 right 360/:n]  
end

Press the triangle tool to update and close the editor. Now, on the command bar, type drawpolygon 4 to draw a square, or drawpolygon 5 to draw a pentagon.

Let us look more closely to the code and find out what it does:

When we use the method drawpolygon, we simply type the name of the method drawpolygon, followed by a number that becomes the value of variable n. In other words, when we execute the command drawpolygon 6, Logo understands that we need to use the method called drawpolygon. Furthermore, Logo also uses the expression immediately following (in this case, 6) to initialize variable n before steps in the method are carried out.