▶ TrainingGet Pro
All tools & lessonsAll toolsAllGet the appApp
Learning departments Music, Math, Cookery, Programming and Art are open – explore →

← Staffroom · Programming

Loops: making the computer do the boring bits

By Mr Babbage, Head of Programming
Mr Babbage, Head of Programming at Classfern
Mr Babbage

Imagine your teacher asks you to write "I will tidy my desk" one hundred times. You would be bored by line ten. A computer would finish in a blink, perfectly, and it would never complain. That is the magic of a loop: you write an instruction once and tell the computer how many times to repeat it, or when to stop.

The idea is older than you might think. In the 1800s, Charles Babbage designed mechanical calculating machines, and in 1843 Ada Lovelace wrote detailed notes on one of his designs. Her notes described a sequence of steps that could be repeated, which is very close to what we now call a loop.

There are two main kinds of loop you will meet:

  • A counting loop repeats a fixed number of times, such as "draw a star 10 times". - A conditional loop keeps going while something is true, such as "keep asking for the password until it is correct".

Loops are everywhere once you start looking. A music app plays the next song in a playlist until the list runs out. A game checks whether you have pressed a button many times every second. A washing machine spins round and round until the timer says stop.

At home or in class, you can practise loops without a computer at all. Write a simple dance as instructions, then wrap part of it in "repeat 4 times" and see how much shorter it becomes. When you do move to a screen, start small: print the numbers 1 to 10, then change one value and print 1 to 100. Watch out for the classic beginner mistake, the never-ending loop, where the stopping condition is never reached.

Try this: Write a loop that counts from 1 to 20, then a second loop that counts back down to 1, and finally change it so it only shows the even numbers.
🎬 A video from Mr Babbage is coming soon.
Mr Babbage
Head of Programming at Classfern. More from Mr Babbage

Comments

Comments open soon. When they do, signed-in parents, teachers and adult learners will be able to comment, and every comment will be checked before it appears.