sciandu
Computer science

Computer science

Loops

Write it once, run it a hundred times: how a program saves work.

What you need first

Imagine you had to write your name a hundred times. You surely wouldn't want to fill out a hundred slips of paper, you'd rather say: just write this a hundred times. Programs know exactly this trick. Instead of writing the same command over and over, they use a loop.

Repeat n times

The simplest loop is the counting loop: repeat something a fixed number of times. Instead of writing the command print Hello five times in a row, you write: repeat 5 times: print Hello. While running, the program counts along and stops exactly after the fifth repetition. You save writing, and if it suddenly needs to be 500 times, you only change a single number.

Loop runner
Repetitions3

repeat 3 times:

draw ⭐

draw 🔷

3 × 2 = 6 shapes
Try it: set the number of repetitions and watch how often the body with its two commands gets executed.

The loop body

Everything inside the loop is called the loop body. One single execution of that body is called a pass. In every pass the body is executed completely from top to bottom, then the next pass begins. The body may contain several commands too: repeat 3 times: take a step, turn around. Then the program does both three times in a row, always in the same order.

How many times does it run in total?

Often you want to know how much a loop gets done in total. For that you multiply: the number of passes times what happens per pass. If a loop repeats a body with 3 commands 4 times, a total of 4 times 3, that is 12 commands, gets executed. You work it out the same way when the body changes a variable: if it adds 2 in every pass, then after 4 passes the variable has grown by 4 times 2, that is by 8. This little calculation will also help you later when you want to estimate how long a program takes.

Exercises

0 of 6 solved

Time to try it yourself. You can't break anything, every attempt counts.

What are loops for?

A program runs: repeat 5 times: print Hello. How many times does Hello appear?

A robot runs: repeat 4 times: take 1 step. How many steps does it take in total?

One advantage of loops: if 5 repetitions suddenly need to become 500, you only have to change .

What happens with the loop body?

Match the terms to their meaning.

Counting loop
Loop body
a pass

Where this leads