For Loops!
Goals:
- Use iteration to avoid typing the same statements over and over
- Make programs less predictable by using the
random
function
Coding Snippets:
- This for loop repeats 3 times. Make it loop more times by changing 3 to a larger number.
- Passing a single integer to
random
causes it to return a value from 0 to one less than that value, e.g., 5 in the case ofrandom(6)
. - There is only one
random
function. However, you can change its argument from 6 to the other options after you drag the block into your code. - Use the output from
random
as input to another function, such aspen
orfd
.
Math and Computer Concepts:
- Put calls to
random
inside a loop to get different results with each iteration
- The syntax
[1..3]
is shorthand for creating the list of numbers[1,2,3]
, formally known as an array. Arrays are a built-in object type in CoffeeScript (the language that underlies Pencil Code). This course will explore arrays, and objects, in future lessons.
Activities:
Use loops to accomplish the following tasks using as few lines of code as possible. Save all programs for today's class in a folder called ForLoops.
- Code a Square, a Decagon, and a Star—but this time use loops!
- Draw a Spirograph by including code to draw a shape within a loop, being sure to turn some amount before the next iteration. The first three shapes below are based on circles, squares, and pentagons. The flower-like patterns are all based on semicircular arcs.
- Program an ErraticTurtle that moves randomly about.
- Create a GrassyField.
- Draw an OceanView. Use for loops to draw the waves.