3. Art – Nested Loops

A nested loop is one which has been placed inside another main loop. Each time the nested loop has finished, further code instructions are normally performed before starting the main loop again.In this way, complex operations can be performed with a just a few lines of code.

Example

This program controls a sprite with two costumes – black and white circles as shown.


Prediction

What will happen when the green flag is clicked.

Write down your prediction.


Run

You can run the project by going to the project page and clicking the green flag


Investigate

Answer the following questions

The nested loop

  1. Which code instructions are inside the nested loop.
  2. How many times does the nest loop repeat?
  3. Which instruction causes the circle to change colour?
  4. How many of each colour circle will the nested loop draw?

The main loop

  1. How many times does the main loop repeat?
  2. Calculate overall how many circles will be drawn?
  3. What happens to the circles each time it completes the main loop?


The whole program

  1. At the beginning the size of the Sprite is set to 150%, and then it is reduced by 5 each time it completes the main loop. Explain why you think these numbers have been chosen.
  2. How many circles do you think you end up seeing? Explain why.

Modify

Modify the program on Scratch to achieve the following.

  1. Change the program so that it draws 5 circles of each colour in the nested loop. Write what you changed.
  2. Change to code so that it only changes colour when it changes size. Write down what you did.
  3. Make it so that the circles start small and get larger. Explain what you did.
    (Hint – you may need to change more than one instruction)


Design

Use this section to plan the design of your art.

  1. Decide what will happen within your nested loop

    e.g. I want it to appear in random positions, start at 120% size and get smaller and rotate 90 degrees
  2. Decide what will change in the main loop before you run the nested loop again

    e.g.I want it to change colour.
    It must go back to 120% size



Hint – You can use Position, Colour, Shape, Rotation, Size, Costume changes.

What you want to achieve in the nested loop, may affect what you need in the main loop.
In the example above, as I want it to start large and get smaller each time, I need to reset the size in the main loop.


Make

Design your own art, by having a go at some of these challenges.

  1. Make a similar art project using a single rectangle costume as the Sprite.
    Experiment using a nested loop with changing the colour, size and turning 90o
  2. Make an art project using two costumes – a solid triangle and a triangle outline. Using a nested loop, change the size, colour, rotation by 180o and costume.
  3. Design your own art project using a nested loop.