Using Loops

In computer science, Loops is a type of block that causes other code to run multiple times in succession.

A program can be written in many different ways that are functionally equivalent. Last week, we learned how to draw shapes using SNAP! As an exercise, we wrote the script to draw a square, which looked like this:

Draw Square Without Loops

As you can notice that the move and turn blocks are repeated multiple times in the script. Although this runs perfectly fine, there are few challenges with it:

  1. Repeated blocks increase the length of the script and reduce the readability. As we move on drawing more complex shapes, the number of repeats will increase, and so do the length of the script.
  2. As the lines of code or the number of blocks in the script increases, the chances of error increases, resulting in a buggy software.

There are multiple ways we can re-write the above program to fix the above-mentioned drawbacks while maintaining the functionality.

For the purpose of this blog, we will use loops. But let’s first understand what are the blocks available to implement loops in SNAP!. There are 3 of them:

  • Repeat Block in SNAP! runs the body of the loop the specified number of times
    • Number of iterations can be a value, variable, or reporter
  • Forever Block in SNAP! runs the body of the loop nonstop until the script is ended
    • Can be stopped either by clicking the stop sign or by any version of Stop all Block in SNAP!
  • Repeat Until Block in SNAP! runs the body of the loop until the specified condition becomes true
    • Save detailed discussion of thisloop until conditionals are introduced

For this example, we will need repeat block and to do use it, we will need to identify the repeating statements and add that in the repeat block, with the number of iterations equal to the number of times we have repeated the statements in the script. Here is what it looks like after using repeat block.

Using Loops - Draw Square Using Loops

Try to recreate it and test with other shapes like triangle and star.

I hope this helped you! Please feel free to share your feedback/questions 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 *