My 2 year old son loves to come up to me and say “Papa, carry me.” and he repeats it over and over again until I ‘buay tahan’ (i.e. give in) and oblige him. Like most human beings, I have a very low threshold for dealing with a request repeated over and over again.
Computers, however, are very good at doing something over and over again without getting bored. The best part is, computers can do it much more quickly than human beings can. We call the computer’s ability to do things over and over again the loop block and it is 1 out of the 7 basic programming concepts that we will go through in the Beginner Computhink for Kids! classes.
What’s the loop block? Let’s try to understand this with something familiar from your daily life. For example, the process of walking. Walking consists of putting your right foot out (or left foot, if you prefer) and putting it on the ground, then the other foot out again, and putting it on the ground. Then you just repeat that over and over again.
Loops – Repeat Action Over and Over Again
However, when you repeat that again and again in programming, the code’s going to look rather long and convoluted. Like the below:
Repeat (this action x times) block
We would improve this by snapping the “repeat 5x” block around the “LeftLeg” and “RightLeg” functions. Ta-daah, meet an example of the loop. Much neater right?
Forever Block with “If” Conditional
Getting from here to there on foot is a loop block of walking again and again until an objective is met. Now, the phrase “until an objective is met” is VERY important whenever you have loop blocks.
The last thing you want to do to a computer program is make it go into an endless loop i.e. the action happens to infinity, or until the computer runs out of memory and crashes. That is a source of pain and misery to be avoided at all cost.
So, whenever a loop block is defined, you would have to think of a logic to “escape” out of the loop block once the objective is met. For example, when you wanted to get a drink, you would walk until you reach the water dispenser, then you stop walking.
Here’s an example of an animation done using loops in Scratch:
And here’s the visual code block:
Notice that we have coupled the forever block with the “If” block to evaluate the conditions when we want to escape. If you recall, the “If” block is another basic programming concept described in our first article on if-else conditional blocks.
Here’s how Mark explains loops:
It’s fun and interesting isn’t it? The Loop Block is one out of the seven basic concepts of programming that we teach in our Beginner Computhink for Kids! classes. Many of the games that your kids will build and play in our classes make use of the loop blocks to control actions.
Next up in Part 3, we’ll explain how we get the computer to do an action when it receives Events!
Laura enjoyed creating short animations and that there was an end product at the end of each lesson to fiddle with.