On this page, you will use abstraction to nest your triangle script inside itself as you learn about recursion.
Does all that copying and pasting of triangle scripts feel awkward to you? You know a better way: abstraction. In Unit 1, you used a pinwheel
block to implement the similar programs asterisk
and polygon
rather than copying the code. Here, you can use a block to manage the abstraction too. But in this case, we want the similar code (a smaller triangle) nested inside, so we will actually use the same block inside itself, a process called recursion.
block called nested triangle
that takes one input, size, and, for now, only draws one triangle, but only if size > 9. (Leave out the code about changing colors.)
When you're building a new block, you can use any color you want. This block is purple so that it will stand out when you use it in a script later.
Click for hints about building a nested triangle
block.
So far, this is just a triangle procedure, but next you'll make it recursive.
Calling a procedure from inside itself is called recursion.
On the previous page, you dragged a copy of the triangle script in between the move
and turn
blocks. You can do a similar thing with your nested triangle
block.
nested triangle
into the definition of nested triangle
between the move
and turn
blocks. Make its size input half the current value of size.nested triangle
in its own definition; this makes it a recursive procedure. Recursion is one of the most powerful techniques in computer science and you will learn more about it in later projects.nested triangle
as a model to define a recursive nested square
block.for
to make an animation that cycles through different turning angle arrangements (that is, 0° and 120°, then 1° and 119°, then 2° and 118°, etc.).