Loops

Now we will learn about loops. The loops we will use are in the “Control” tab, just above the if statements. We will start with the forever loop. We will create a variable named Test and have it so that when we press the green flag it will set Test to 0. Then we will use the forever loop to repeatedly add one to Test. We will put a “forever” loop below the “set Test to 0” block. And then inside of that we will use the “change Test by 1” block.

Try it out.

Note: this program will not stop. To stop it press the red stop sign next to the green flag in the top right corner.

 

You may have noticed that Test seems to change by a lot of numbers at once, but we only told it to change one at a time. Since the program is running so fast in a short amount of time it will change by a lot, so it looks like it changes by big jumps. We will add a “wait 1 sec” block inside of the forever loop to slow it down so we can see what is happening.

Try it out.

Now we will change the forever loop to a “repeat 10” loop. This one will repeat the code for 10 times and then stop. You can change the number to have it repeat for a different number of times.

Try it out.

And lastly is the “repeat until” loop. This one is kind of like an if statement, except it will keep repeating the code until it is true. For example while I am not full, I will eat more food. Let’s replace the “repeat 10” loop with this “repeat until” loop. But we need to add the condition to the loop. We will have it repeat until Test is 5.

 

Try it out.

Challenge: Use a loop (your choice of which one) to make Test equal to 100 once it is done looping. You may need to adjust the time and/or the amount to change Test by.