Skip to content

4. Use a Loop to Draw Multiple Shapes

Playback Speed:
Transcript

In the previous video, you wrote code to create a shape on the first slide of your presentation.

In this video, you will add shapes equaling the number of slides in your presentation and program them to fill with color as your presentation progresses.

The type of loop that you will use is called a for loop.

A for loop runs code repeatedly using different values.

For your progress bar, one loop will use a value for each slide, and the other loop will use a value for each of the shapes on a slide.

Both for loops will start above the line of code that draws a shape.

Put your cursor at the end of that line, and press enter.

Type the word for and an open parenthesis.

For loops have three parts: first, declare a variable to hold the initial value.

In this case, it’s v-a-r-i equals zero.

Then, add a semicolon.

Next, tell the program how long to run the loop.

Type i is less than slides.

Add a period, and select length.

Then, add a semicolon.

This tells the program to stop running the loop once i is less than the number of slides in the presentation.

Now, tell the program how much to change i each time the loop runs.

Type plus, plus, i Add a closed parenthesis and an open curly brace to hold all the code inside the loop.

Next, place your cursor at the end of the line of code that adds the shape to your presentation.

Press enter, and add a closed curly brace on the following line.

Remember to match your code with what you see on screen exactly.

Good job.

Your first loop is complete!

It starts by setting the value of i to zero and runs until i equals the number of slides in the presentation.

So each time the loop runs, i increases by one.

In this example, you have five slides in your presentation, so first, i is zero; then it’s one, two, three, and four.

The loop will run five times -- the number of slides in your presentation, but the code inside the loop hasn’t changed, so if you run the loop, it will draw five shapes in the exact same spot on the first slide.

See for yourself. Save and run the program.

Then, go to the first slide of your presentation.

Click and hold to move them around.

Delete all of the shapes, so you start with an empty slide in the next video.

If you don’t see five shapes or get an error message, make sure your code matches what you see on screen exactly.

Then, move on to the next video to create a second loop that places your shapes in the right spot!

Now it’s your turn: program a for loop, save and run your program, delete all of the shapes, troubleshoot any errors, and move on to the next video to code your second loop.

Next
Instructions
  1. Program a “for” loop.
  2. Save and run your program.
  3. Delete all of the shapes.
  4. Troubleshoot any errors.
  5. Move on to the next video to code your second loop.