Using Nested Loops

In the blog post, Using Loops, we discussed that loop is a type of block which is used to run code multiple times. It is useful in reducing code redundancy and increase readability when dealing with repetitive tasks.

Continuing to build on the example of drawing a square, what if now we were to draw two squares next to each other? What would that code look like?

Here is the simple straight forward solution to this problem in SNAP!:

Using Nested Loops - Draw two squares

So far so good!

But what if we were to build a wall of squares? It will require 100s and 1000s of squares next to each other. Should we duplicate the code to draw one square as many number of squares we need? Well, if we have to do that, we run into the same problems of increase in code redundancy and decrease in code readability.

However, there is a simpler solution to this problem. We can use nested loops instead.

What is a nested loop?

As the name suggests, a nested loop is a loop inside the body of another loop. Once you define a loop inside the body of another loop, the inner loop runs all it’s iterations each time the outer loop runs (unless specifically instructed to exit the loop, which we will not discuss in this post).

So let’s re-write the above example to draw a square 2 times using nested loops. This is what it will look like:

Draw two squares Using Nested Loops

Question: How many times will the sprite move in this example?

Post your response in the comments below.

Share This:

A geek, a techie, a daughter, a sister and a wife. Worked at Microsoft for 8 years and currently working at Amazon Web Services (AWS). All opinions expressed here are my own and has no correlation to my employer or ex-employers!

Leave a Reply

Your email address will not be published. Required fields are marked *