Nested Loops

We can also put Loops inside Loops - this is called Nesting Loops or Nested Repetition.

For example, create a separate stack of blocks to your blocks that make the Cat dance, that look like this:


Click the stack of blocks and count the drum beats. You should hear 8 drum beats. 

Why does this happen?

  • The repeat (4) block repeats the actions inside the Loop four times,
  • these actions being the repeat (2) Loop, which in turn plays the drum noise 2 times.

Therefore, the drum noise is played 8 times in total.

So, when you have two nested repeat loops, the actions inside the inner loop block (play drum (1 v) for (1) beats in the example above) will repeat for the number in the outer repeat loop (4 in the example above) multipled by the number in the inner repeat loop (2 in the example above).

We are now going to add an extra step to our Dancing Cat program.

Now, we are going to change the dance so that

  • the Cat will move forth and back twice,
  • a hi-hat noise will be played for 1 beat
  • and the Cat will then repeat these steps.

To do this, we will need to use Nested Loops.

The program to make the Cat dance should be changed to look this:


Now when you click the stack of blocks, the Cat should:

  1. move to the right and play a snare drum noise
  2. move back to the left and play a snare drum noise
  3. repeat the last 2 steps
  4. play a hi-hat noise

Then the Cat will go through steps 1-4 again.


Views
1 Total Views
1 Members Views
0 Public Views
Share on Social Networks
Share Link
Share by mail

Please login to share this webpage by email.