What are loops?
We’ve already seen one type of loop used in Scratch, the forever loop. As the name “loop” implies, a loop repeats the code in its body. Loops are useful when programmers want to run code multiple times, but don’t want to write the same code over and over again. Some concepts from if-statements carry over to loops. Loops also have a condition; the main difference is that if-statements only run code once if the condition is true, but loops repeat code while the condition is true. “If you’re cold, put on a jacket” occurs once. “While you are thirsty, keep drinking water” occurs as long as you’re still thirsty.
Writing a Loop in Scratch
The set-up for a loop is similar to the set-up for an if-statement, but unlike the if-statement, a forever loop isn’t required. The loop is already repeating. Like always, drag a “When ⚑ clicked” block into the script area to indicate the start of the code. Then, go to the Control section of the block palette, and clip a “repeat until < >” block onto the flag block. This block repeats its body until a condition is satisfied. In other words, when the condition hasn’t been satisfied, the block repeats its body.
Answer : When you start running the code, the cat sprite will move forwards until it reaches the edge of the screen!
If-statements and loops are widely used programming concepts that can be used to create many different projects. Although they both rely on conditions, they have different uses. The code below combines if-statements and loops. See if you can predict what the following code will do!
You can now make simple games on your own, happy coding!