Lesson 9: Looping and Random Numbers

Overview

Students learn to use random values and looping to create variation in their drawings and quickly duplicate objects they wish to appear in their digital scenes many times. Students will be presented with a version of the for loop which only enables them to change the number of times the loop runs. This block is essentially a "repeat" block and will be presented that way. Students will also be presented with blocks which enable them to choose a random number within a given range. Together these blocks enable students to create more complex backgrounds for digital scenes by randomly placing simple objects within the background of their scene. Students use these tools to step through the Under the Sea exemplar digital scene.

Purpose

Loops are a relatively straightforward idea in programming - you want a certain chunk of code to run repeatedly - but it takes a little practice to get good at controlling loops and recognizing how and where in your programs to use them. The for loop in JavaScript (and many other programming languages) is designed to be used for both simple and sophisticated programming tasks, thus it has a lot of syntax to it that will be explained in the future. In this lesson, the block-based form of the for loop exposed to students is effectively a simple repeat loop - it only lets them change a number that dictates how many times the loop repeats.

Random numbers are also used more (much more) in this lesson as an effective way to experiment with loops. Creating some randomly-generated output with each iteration of the loop is good visual feedback that the loop is running the way you expect. It also helps you explore the ranges of possible outputs, which tells you more about what your program can and cannot do.

Agenda

Getting Started (2 minutes)

Activity (30 minutes)

Wrap Up (10 minutes)

Assessment

Extended Learning

View on Code Studio

Objectives

Students will be able to:

  • Use a loop in a program to simplify the expression of repeated tasks.
  • Identify appropriate situations in a program for using a loop.
  • Use random values within a loop to repeat code that behaves differently each time it is executed.

Preparation

  • Set up the room for computer use
  • Plan how you want students to watch the video on loops

Links

Heads Up! Please make a copy of any documents you plan to share with students.

For the Teachers

For the Students

Vocabulary

  • For Loop - Loops that have a predetermined beginning, end, and increment (step interval).
  • Loop - The action of doing something over and over again.

Teaching Guide

Getting Started (2 minutes)

Purpose

Students will have an opportunity to explore the process of creating loops by programming with them in App Lab. Use the Getting Started Activity to motivate the need in some programs to repeat commands many times, and foreshadow the fact that random inputs can be used in repeated commands to rapidly develop a variety of behaviors.

Loops versus Functions

Remarks

As we have developed as programmers, we have focused on the process of breaking down large tasks into smaller pieces and assigning each piece a function.

When we break down a large task, often we will find that some portion of the task needs to be repeated many times. As programmers, we would simply call the same function many times. This might work if we need to call the same function five times, but if that function needs to be run 1,000,000 times, we’ll need a better solution.

Today we’ll be exploring how a programming construct called a loop solves this problem by allowing us to repeat a set of commands many times.

We’ll also practice looping through commands many times with random input, therefore giving us many instances of random output.

Just as we saw yesterday, this will be both useful for testing our code and also for developing more variety in our drawings.

At the end of class we'll ask: "When should you use a loop instead of a function, or vice versa?"

Activity (30 minutes)

Improving Under The Sea with Loops

  • Today we'll learn how to use something called a "for loop"
  • The for loop is a JavaScript programming construct - it looks and works the same here as it does in "the real world".

Wrap Up (10 minutes)

When to use loops versus functions

Having used loops to repeatedly run a smaller portion of a larger program, students should attempt to formalize their understanding of when a loop should be used.

Discussion Goal

Important points to draw out are related to when to use a function v. when to use a loop. While you can get code to function similiarly with a function or a loop the general rule of thumb is:

  • Write a function when you have a piece of code - a procedure - that you might reuse in other places in your program.
    • A function might also help you encapsulate a solution to a common problem in one place that you can call on repeatedly with different inputs (e.g. drawSquare(size))
    • Writing a function is often more of a design decision. You are trying to encapsulate and abstract details so you think about other parts of a larger program
  • Write a loop when there is something you need to do over and over again and it doesn’t make sense to split it up any more.
    • Writing a loop is more of an algorithmic decision - you actually just need repetitious behavior to solve some problem.
    • For example, we don’t want to manually call functions many times in a row. If you’re calling the same function many times in a row, it’s time to make a loop.

Reflection: Students should briefly journal and share responses to the following question:

  • "Develop a rule for deciding when to use a loop within a program. Perhaps think about when to use a loop versus a function. Try to make connections to Top-Down Design in your response. Below your rule, write a couple sentences justifying your rule."

Share Responses:

Once students have written their responses, have them share with a neighbor and ask a few students to share their rules with the class. Focus in particular on the reasons for using a loop.

For example:

  • “Use a loop when there is something you need to do over and over again and it doesn’t make sense to split it up any more.”
  • “We don’t want to manually call functions many times in a row. If you’re calling the same function many times in a row, it’s time to make a loop.”

Assessment

Project:

For students’ individual renderings of the Under the Sea project, it’s recommended that you simply check for completion and that the final version students submit contains all of the required features. In the next lesson, students create their own scene from scratch, and that project has a complete rubric for a more formal assessment.

Questions:

Multiple Choice:

8 Squares Drawing A programmer wants to write a program in which the turtle draws 8 squares in a row while moving forward. The final result should look like the turtle drawing shown at left. Program Code

But something is wrong! The incorrect code is shown to the right. The programmer has attempted to write a function to draw a single square. Then he wrote another function that attempts to call that function 8 times. Mentally trace through the code and determine which line of code should be removed to make the program do what it's supposed to.

  • A: 1
  • B: 5
  • C: 6
  • D: 7
  • E: 14

Free Response:

When breaking a problem down, you often encounter elements that you want to use repeatedly in your code. Sometimes it's appropriate to write a new function; at other times it's appropriate to write a loop. There is no hard-and-fast rule as to which is better, but what do you think? What kinds of circumstances would lead you to writing a function versus using a loop?

Extended Learning

Students can extend their digital scene by manipulating the random values used as inputs to the different components of the scene or adding additional functions for drawing new figures. At the end of the progression, students are given a separate level in which to do so.

  • Using Loops
  • 2
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Getting Started with Loops

A loop is a block of code that is repeated or "looped through" in a program. You will be creating a loop using the for loop block.

We'll start by experimenting with a program similar to what you saw in the video.

Do This:

  • Drag out a for loop block.
  • Inside the loop:
    • Add a call to moveForward.
    • Add a call turnLeft. (HINT: try turning by 137 degrees to start. You can change after that.)

  • Run the program to see the loop in action.
  • Experiment:
  • Change the number of times the loop runs.
  • Increase the run speed to see how fast loops can execute.
  • How many times can the loop run before you can no longer tell the difference in the image?

Move on once you feel like you have a decent grasp of using a for loop: setting the number of times to repeat, running the program, and setting the run speed.

View on Code Studio

Student Instructions

Practice Using Loops - Part 2

Let's look at the second example from the video.

Use a for loop to call a function that you wrote. We've provided the code for the drawSquare function for you.

Drag out a for loop.

Inside the loop add a call to drawSquare, and a call to turnRight.

Run the program to see what's happening.

Do This:

Change the number of loop iterations to draw a lot of squares. Try to create the figure shown below (or something similar). HINT: the image below has 72 squares in it.

Once you've played enough to get the hang of calling a function from inside a loop then move on.

View on Code Studio

Student Instructions

Code Trace

In 1-2 sentences, explain what you think the following code does.

View on Code Studio

Teaching Tip

Validation note: we don't check to see if the screen is filled. We only check that some loop is runs at least 1500 times.

Student Instructions

Now try it: Looping with Random Values

If you add some randomness to turtle behavior inside a loop, the program will run a little differently every time which can make for some cool effects.

You're about to see a program in which the turtle moves to a random location each iteration of the loop, and draws a randomly-sized dot that also has a random color. We've also made the dot semi-transparent by setting the alpha value to 0.5 (50% transparency).

Do This:

Figure out how many iterations (number of times the loop runs) you need to consistently fill the screen entirely with dots so none of the background is showing. It will be a little different every time so you'll need to experiment.

Compare what you found with a neighbor to see how close your results are. Then move on.

View on Code Studio

Teaching Tip

Validation note: here's what is checked on this level:

  • Two loops are present
  • The loops are not "nested" - i.e. one loop inside the other.
  • That the sum total number of iterations is greater than 2500. (It probably needs to be more than this to actually work. This is just a minimal check).

Student Instructions

Using Multiple Loops

Some repeated tasks can't easily be solved with a single loop. Instead, you'll need to use one loop after another, each one solving a part of the problem.

Do This:

Add a loop to fill the screen with semi-transparent white dots until the original dots are "erased".

  • Drag a second loop into your code that will run after the first loop.
  • Add commands to draw dots in random locations that are white with opacity set to 0.5.
  • Increase the iterations so that the colored dots are totally erased. How many does it take?

HINT: you can copy/paste the original loop and just change the color of the dots and number of iterations.

View on Code Studio

Student Instructions

Top-Down Design

Look at this complex version of the "Under the Sea" scene you drew in the previous lesson. You now have all the skills you need to recreate this digital scene.

We will use Top-Down Design to help manage the complexity of drawing this image. The starter code you will be provided already has broken the problem into multiple levels.

Overview of Program Structure

You are about to see that we've provided you with a good amount of starting code. Here's a brief tour:

High-Level Function Calls: These read almost like a story of how you will draw the image. There's one function for every major component of the scene.

High-Level Function Definitions: These currently draw a single copy of each component. You will add code to these functions to draw many copies of each component in a variety of sizes and colors.

Low-Level Functions: These draw single elements of the scene. Most have been written for you already, but we've left a few for you to complete as well.

Do This:

  • Review the structure of the code in this level.
  • Run the code to familiarize yourself with what it currently draws.
  • When you are ready to do so, move on!
View on Code Studio

Teaching Tip

Validation note -- We check to verify that the student:

  • Added a loop to the drawAllBubbles function
  • That drawBubble is called inside a loop that runs at least 200 times.

Student Instructions

Add Bubbles

The first high-level function you will write is drawAllBubbles. You may have noticed that the bubbles in the image look very similar to the dots example we've already drawn in this lesson. Now we'll use that skill to add to our image.

Do This:

  • Read the drawBubble function to know how it works and what parameters it accepts.

  • Modify the code of drawAllBubbles:

  • Add a loop inside the function.
  • Move the commands that were already inside the function inside the loop instead -- In other words "wrap a loop around the existing lines of code that are inside the function. This way your code will move the turtle randomly and call drawBubble many times.
  • Set the number of iterations in your loop so that the screen is filled with bubbles. Try starting with 200 and then adjust to whatever number you like.
View on Code Studio

Teaching Tip

Validation note -- We check to verify that the student:

  • Added a loop to the drawAllFish function
  • That drawFish(size, r, g, b) is called inside a loop that runs at least 15 times.
  • That none of conditions from previous levels have been violated (number of bubbles, etc.).

Student Instructions

Add Fish

The next high-level function you will write is drawAllFish. A version of drawFish with parameters has been provided for you to use.

Do This:

  • Read the drawFish function to know how it works and what parameters it accepts.

  • Add a loop to drawAllFish.

  • Place the commands already inside the function in your loop. This way your code will move the turtle randomly around the top 360 pixels of the image and draw 15 fish of random size between 5 and 20 using drawFish.

  • Once you have your loop working try calling drawFish with random values for its red, green, and blue parameters to get differently colored fish.

View on Code Studio

Teaching Tip

Validation note -- We check to verify that the student:

  • Added a loop to the drawAllSeaStars function
  • called drawSeaStar inside a loop that runs at least 5 times.
  • That none of conditions from previous levels have been violated (number of bubbles, fish, etc.).

We do not check whether drawSeaStar uses a loop as part 1 of the instructions indicate.

Student Instructions

Add Sea Stars

We're now ready to add sea stars to our image by writing drawAllSeaStars. Recall that we've already written loops to draw much more complex stars.

Do This:

  • Read the drawSeaStar function to know how it works and what parameters it accepts.

  • First: Update drawSeaStar to use a for loop

    • drawSeaStar has a portion of code that uses a longer sequence of repetitious single commands.
    • Find the pattern and "wrap a loop" around it so that the repetition is done with a loop rather than many lines of declarative function calls.
  • Second: Add a loop to drawAllSeaStars.

    • Place the commands already inside the function in your loop. This way your code will move the turtle randomly around the bottom pixels (y values between 360 and 450) of the image.
  • Draw 5 sea stars of random size between 10 and 30 using drawSeaStar.

View on Code Studio

Teaching Tip

Validation note -- We check to verify that the student:

  • made a call to a 2-param version of drawSeagrass(radius, numWaves). The order of the parameters does not matter for our check - only that a 2-param version was called.
  • That none of conditions from previous levels have been violated (number of bubbles, etc.).

Student Instructions

Controlling Loops with Parameters

This time you will modify one of the lower-level functions - drawSeagrass. Notice that the current version of drawSeagrass actually uses a loop. We want to modify this function so that we control the number of times it loops with a parameter.

Do This:

  • Look at the drawSeagrass function to see how it currently works.

  • Add a parameter that will be used to indicate how many waves the seagrass makes.

  • Modify the 'for loop so that it uses that parameter as the number of times to repeat.

  • Finally, modify drawAllSeagrass to call this new two-param version of drawSeagrass supplying a reasonable random value for the second parameter as well.

View on Code Studio

Teaching Tip

Validation note -- We check to verify that the student:

  • Added a loop to the drawAllSeagrass
  • Called drawSeagrass(radius, numWaves) at least 30 times.
  • That none of conditions from previous levels have been violated (number of bubbles, etc.).

Student Instructions

Add Seagrass

Our new version of drawSeagrass now draws a single piece of seagrass with a random height. Now let's use a loop in drawAllSeagrass to fill the sea floor with it.

Do This:

  • Add a for loop to drawAllSeagrass that draws about 50 pieces of seagrass using your updated drawSeagrass function.
View on Code Studio

Teaching Tip

Validation note -- We check to verify that the student:

  • Added a loop to the drawAllSumbeams
  • Called drawSunbeam at least 75 times.
  • That none of conditions from previous levels have been violated (number of bubbles, etc.).

Student Instructions

Add Sunbeams

Finally, we'll add some visual flourish by writing drawAllSunbeams. Note: The turnTo command makes the turtle face a random direction prior to drawing each sun beam.

Do This:

  • Read the drawSunbeam function to know how it works and what parameters it accepts.

  • Add a loop to drawAllSunbeams to draw about 100 sunbeams. Inside your loop:

  • Place the commands already inside the function in your loop. This way your code will move the turtle to a random x location at the top of the image (y is 0), turnTo a random angle between 165 and 175 degrees, and call drawSunbeam.

  • Project: Under the Sea
  • 15
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Validation Note: We have turned off most validation here to allow for free play. We check that the code isn't blank, but only the following:

  • At least 5 loop initializations (a full project would have ~50 or more)
  • At least 100 loop interations (a full project would have more than 500)

Student Instructions

Free Play!

(Optional)

Mess around with your "Under the Sea" scene to make it do different things.

Ideas: Make different amounts of each component. Play with the ranges of random values. Add other creatures. Play with color values to give the scene a different feel (nighttime? red dawn?). * Get creative!

Don't Worry... You Can't Screw It Up

  • Play around as much as you want - you can always go back to a previous version.
  • Each time you hit "Run" your code is saved in a way that lets you get back to it.
  • Notice that there is button at the top of the page called Version History that lets you see and use any previous version of your code.

  • AP Practice Response - Identify the Abstraction
  • 16
  • (click tabs to see student view)
View on Code Studio

Student Instructions

AP Practice - Identify the Abstraction

One component of the AP Create Performance Task is selecting an abstraction that you developed.

3. Program Code
  • Mark with a rectangle the segment of program code that represents an abstraction you developed.


Here's the scoring guide for this question

Choose the Student-Created Abstraction

The program code below is from a program a student developed.

Write which of the rectangles (A, B, C, or D) is placed around a student-developed abstraction.

Then explain your answer using the criteria in the scoring guide.

  • Check Your Understanding
  • 17
  • 18
  • 19
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Correct answer: Line 7.

The turnRight on line 7 will re-orient after drawing each square, which causes the turtle to not travel straight forward drawing squares. Since the drawSquare function has the turtle finish at the same location and facing the same direction that it started, all that needs to happen after drawing each square is to move forward.

Student Instructions

Multiple Choice: Code Trace

A programmer wants to write a program in which the turtle draws 8 squares in a row while moving forward. The final result should look like this:

But something is wrong! The incorrect code is shown below. The programmer has attempted to write a function to draw a single square. Then he wrote another function that attempts to call that function 8 times.

Mentally trace through the code and determine which line of code should be removed to make the program do what it's supposed to.

View on Code Studio

Student Instructions

When breaking a problem down, you often encounter elements that you want to use repeatedly in your code. Sometimes it's appropriate to write a new function; at other times it's appropriate to write a loop.

There is no hard-and-fast rule as to which is better, but what do you think? What kinds of circumstances would lead you to writing a function versus using a loop?

View on Code Studio

Student Instructions

Design a program

Describe, using a top-down approach, how you would create a program to draw a white snowflake on a blue background that uses random numbers, so the snowflake will be unique every time you run the code.

You don’t need to write the exact code or blocks that you would use, but you should describe what functions you would need to create, where you would or would not use loops, and where you would or would not use random numbers.

Standards Alignment

View full course alignment

CSTA K-12 Computer Science Standards (2011)

CL - Collaboration
  • CL.L2:3 - Collaborate with peers, experts and others using collaborative practices such as pair programming, working in project teams and participating in-group active learning activities.
CPP - Computing Practice & Programming
  • CPP.L2:5 - Implement problem solutions using a programming language, including: looping behavior, conditional statements, logic, expressions, variables and functions.
  • CPP.L3A:3 - Use various debugging and testing methods to ensure program correctness (e.g., test cases, unit testing, white box, black box, integration testing)
  • CPP.L3A:4 - Apply analysis, design, and implementation techniques to solve problems (e.g., use one or more software lifecycle models).
CT - Computational Thinking
  • CT.L2:6 - Describe and analyze a sequence of instructions being followed (e.g., describe a character’s behavior in a video game as driven by rules and algorithms).
  • CT.L3A:1 - Use predefined functions and parameters, classes and methods to divide a complex problem into simpler parts.
  • CT.L3A:3 - Explain how sequence, selection, iteration, and recursion are building blocks of algorithms.
  • CT.L3B:4 - Evaluate algorithms by their efficiency, correctness, and clarity.

Computer Science Principles

4.1 - Algorithms are precise sequences of instructions for processes that can be executed by a computer and are implemented using programming languages.
4.1.1 - Develop an algorithm for implementation in a program. [P2]
  • 4.1.1D - Iteration is the repetition of part of an algorithm until a condition is met or for a specified number of times.
5.1 - Programs can be developed for creative expression, to satisfy personal curiosity, to create new knowledge, or to solve problems (to help people, organizations, or society).
5.1.2 - Develop a correct program to solve problems. [P2]
  • 5.1.2B - Developing correct program components and then combining them helps in creating correct programs.
  • 5.1.2C - Incrementally adding tested program segments to correct, working programs helps create large correct programs.
5.3 - Programming is facilitated by appropriate abstractions.
5.3.1 - Use abstraction to manage complexity in programs. [P3]
  • 5.3.1A - Procedures are reusable programming abstractions.
  • 5.3.1C - Procedures reduce the complexity of writing and maintaining programs.
  • 5.3.1D - Procedures have names and may have parameters and return values.
  • 5.3.1F - Parameters generalize a solution by allowing a function to be used instead of duplicated code
  • 5.3.1G - Parameters provide different values as input to procedures when they are called in a program.
  • 5.3.1L - Using lists and procedures as abstractions in programming can result in programs that are easier to develop and maintain.
5.4 - Programs are developed, maintained, and used by people for different purposes.
5.4.1 - Evaluate the correctness of a program. [P4]
  • 5.4.1C - Meaningful names for variables and procedures help people better understand programs.
  • 5.4.1D - Longer code blocks are harder to reason about than shorter code blocks in a program.
  • 5.4.1E - Locating and correcting errors in a program is called debugging the program.
  • 5.4.1F - Knowledge of what a program is supposed to do is required in order to find most program errors.
  • 5.4.1G - Examples of intended behavior on specific inputs help people understand what a program is supposed to do.
  • 5.4.1H - Visual displays (or different modalities) of program state can help in finding errors.
  • 5.4.1I - Programmers justify and explain a program’s correctness.
  • 5.4.1J - Justification can include a written explanation about how a program meets its specifications.
  • 5.4.1K - Correctness of a program depends on correctness of program components, including code blocks and procedures.

CSTA K-12 Computer Science Standards (2017)

AP - Algorithms & Programming
  • 3A-AP-15 - Justify the selection of specific control structures when tradeoffs involve implementation, readability, and program performance and explain the benefits and drawbacks of choices made.