Review Polygon
- Want to draw a hexagon withh circuference 400:
- Need to calculate the move distance: 400 / 6 = 66.67
Need to calculate the turn angle: 360 / 6 = 60
function main() for 0 <= i < 6 do ♻turtle → forward(66.67) ♻turtle → left turn(60) end for end function
Arithmetic
- Now, what if we want a pentagon instead
- Need to change the iterations, the forward distance, and the turn angle turning the same amount 5 times
But there is a better way, let the program do the math
function main() for 0 <= i < 6 do ♻turtle → forward(400 / 6) ♻turtle → left turn(360 / 6) end for end function
- Now we can change the shape just by changing all of the sixes to fives
Anywhere you can put a number, you can put a mathmatical equations as well
Variables
- But changing all three of those variables is a bit of pain, and prone to making mistakes in a large program
- Again, there is a better way, named values, also called variables
- We can name the 5, according to what it represents, in this case the number of sides
Replace all of the fives with the variable name
function main() var number of sides := 5 for 0 <= i < number of sides do ♻turtle → forward(400 / number of sides) ♻turtle → left turn(360 / number of sides) end for end function
- And changing the shape is as simple as changing one number in the program
- Added bonus, it’s easier to read
- We can make it even more easy to read by using another variable
Replace 400 with the name circumference
function main() var number of sides := 5 var circumference := 400 for 0 <= i < number of sides do ♻turtle → forward(circumference / number of sides) ♻turtle → left turn(360 / number of sides) end for end function
- Now it is also easy to change the size of the polygon
- Note, the order matters; must declare the variable’s value before using the variable name
- Can also use variables names in the definition of other variables names
The code would be even more readble with variables for the edge length and turn angle
function main() var number of sides := 5 var circumference := 400 var edge length := circumference / number of sides var turn angle := 360 / number of sides for 0 <= i < number of sides do ♻turtle → forward(edge length) ♻turtle → left turn(turn angle) end for end function
Quiz
- socrative.com.
- Room name ‘INQ241’