What are loops?

Loops are how computers repeat tasks over and over again without getting tired or bored. Imagine you are brushing your teeth. You put toothpaste on the brush, scrub the top teeth, scrub the bottom teeth, rinse, and then repeat until your mouth feels clean. That repeating part is a loop. It keeps going until it hits a stop condition, which is just like looking in the mirror to see if the foam is gone. If there is still foam, you keep looping.

Types of Repetition

Computers use loops differently depending on what they need. One kind is called an for loop. Think of it like eating four cookies from a jar. You start with four cookies in your hand and eat them one by one until the count reaches zero. The computer counts exactly how many times to repeat, just like you counting "one, two, three, four."

Another kind is the while loop. This is like waiting for your popcorn to finish popping. You keep listening until the noise stops or the timer runs out. You do not know exactly when it will end, but you keep doing the action (waiting) as long as a certain condition is true. If the popcorn keeps making noise, you keep standing by the machine.

A loop without a stop rule can go on forever, which we call an infinite loop. It is like a dog chasing its tail in circles until it gets dizzy and stops.

Take the quiz →

Examples

  1. Spinning around on a playground merry go round
  2. Eating bites of an apple until it is gone
  3. Counting steps while walking up stairs one by one

Ask a question

See also

Discussion

Recent activity