Repeating things
Computers don't get bored
While computers can't think, they can repeat tasks over and over again and never get bored.
What might the output of this be?
OK computer: repeat 5 times: display "Hello!"
- Hello!Hello!Hello!Hello!Hello!
It'd take a huge amount of time to handle repetitive tasks if computers couldn't repeat them.
Making two sandwiches
Imagine you wanted to make sandwiches for you and a friend. It sounds simple, but it already involves some repetitive tasks.
get 4 slices of bread put peanut butter on slice 1 put peanut butter on slice 2 put jelly on slice 3 put jelly on slice 4 press slices 1 and 3 together press slices 2 and 4 together
Complicated, huh? Just imagine you were to make sandwiches for ten or more people!
Making ten sandwiches
Now, let's actually make ten sandwiches with a little big shortcut!
repeat 10 times: get 2 slices of bread put peanut butter on slice 1 put jelly on slice 2 press slices 1 and 2 together
There they are: ten sandwiches, computer-crafted.
Loop de loop
These shortcuts are known as loops (because they loop back to steps). As a programmer, it's up to you to find repetitive tasks and wrap them in loops.
Can you think of repetitive tasks?
- Counting from 0 to 10
- Deleting all the files in a folder
Great! If the same or similar instructions follow each other, it might be good idea to wrap them in a loop.
Count-controlled loops
Quite often, a sequence needs to be repeated for a set number of times.
pump in water repeat 72000 times: rotate washing machine drum then pump out water
Fantastic! Count-controlled loops come in handy when you know exactly how often the sequence has to be repeated.
Condition-controlled loops
At times, however, you might not know how often a sequence has to be repeated.
This breakfast sequence is an example.
get a bowl, cereal, and milk pour cereal into the bowl pour milk into the bowl repeat until the bowl is empty: spoon the bowl contents into the mouth
Sweet! Condition-controlled loops repeat sequences while or until a condition is met.
Shopping sprees
Can you think of a way to loop through a shopping list and speed up a shopping spree?
get a basket repeat for every item on the list: find the item put the item in the basket then proceed to checkout
Fantastic! That way, you'll be at the checkout counter in no time.
Comments