Overview
In this lesson, students will be introduced to the idea of randomly choosing elements from arrays.
Overview
In this lesson, students will be introduced to the idea of randomly choosing elements from arrays.
Suggested Duration
45 minutes
Objectives
Students will be able to:
Student Outcomes
Abstraction:
Algorithms:
Prototype:
Vocabulary
Array | An ordered series of data |
---|---|
Index | A position within an array |
Element | A piece of data within an array |
Zero-Indexed | The first element of an array has an index of 0, not 1 |
For Loop | Loops through a block of code a number of times |
Iterate | To go through elements one by one |
Resources
Arrays and Loops
We learned about loops recently -- they let you repeat a piece of code many times over. It turns out that loops are especially useful and powerful when joined with arrays! Let’s think of a real-world example.
Say you have a list of all your friends and their heights. You’re an artist, so you like to draw your friends to perfect scale. In real life, you would go through the list, read the height, and draw your friend. You’d be repeating your steps for each member of the list. This is a real-life loop! It’s something you can easily do in code, too -- you can write code to draw objects based on some elements stored in an array.
Review: For loops start by initializing a variable, then they check for a condition, increment the variable, and execute a task until the condition is met.
Let’s look at an example using colors!
We want to be able to draw three rectangles in a row.
So in order to draw each rectangle:
Remember, the “i” variable is the current index of the array on that iteration through the loop.
Exercise #1: Make a rainbow snowman
Scientists have recently discovered a big advance in snowman-building technology. Gone are the days of cheery stovepipe hats and coal smiles. Gone are the days of carrot noses. Modern snowmen, like modern buildings, are one thing, and one thing only: tall.
Scientists have developed a way of creating 7-snowball-high snowpeople that are colored in every shade of the rainbow. Your mission, should you choose to accept it, is to create a rainbow snowman using one, and only one, for loop to determine both the position of each ellipse, the size of each ellipse, and the color of each ellipse. Your snowman should come out looking something like this.
Extensions
Upon clicking, randomize or reverse the order colors or the sizes!