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.
This program controls a sprite with two costumes – black and white circles as shown.
What will happen when the green flag is clicked.
Write down your prediction.
You can run the project by going to the project page and clicking the green flag
Answer the following questions
The nested loop
- Which code instructions are inside the nested loop.
- How many times does the nest loop repeat?
- Which instruction causes the circle to change colour?
- How many of each colour circle will the nested loop draw?
The main loop
- How many times does the main loop repeat?
- Calculate overall how many circles will be drawn?
- What happens to the circles each time it completes the main loop?
The whole program
- 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.
- How many circles do you think you end up seeing? Explain why.
Modify the program on Scratch to achieve the following.
- Change the program so that it draws 5 circles of each colour in the nested loop. Write what you changed.
- Change to code so that it only changes colour when it changes size. Write down what you did.
- 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)
Use this section to plan the design of your art.
- 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
- 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.
Design your own art, by having a go at some of these challenges.
- 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
- 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.
- Design your own art project using a nested loop.