How do loops work in programming
If you want someone to clap a hundred times, you don't write "clap" a hundred times. "Clap, a hundred times" is enough. A loop means writing a task once and having it done many times, and it's what computers do best.
A hundred lines vs one line
Say you want "clap" done five times.
Writing it by hand means writing "clap" on five lines.
With a loop, one line does it: "clap, five times."
Below, you can compare the two side by side.
Five lines by hand vs one loop line. A loop states what to do and how many times in one line.
Five times is still easy enough to write by hand.
But a hundred times, or a thousand? Not by hand.
A loop writes "what, how many times" just once, and the computer repeats the rest.
Repeating while counting
A loop usually counts as it goes around.
One, two, three... it does the same task until it reaches the set number.
Press the button below and stamps appear one by one, as many as you set.
Repeat the same task a set number of times. Each count adds one stamp, and it stops at five.
Do the same task once for every count: that's the basic loop.
Set how many times, and the computer repeats it exactly that many times without getting tired.
Climbing to the top
Sometimes, instead of a count, you set "until when."
Like climbing stairs to the top: "if you're not there yet, go one more."
That "not there yet?" is the condition we learned earlier: if true, do it again; if false, stop.
Repeat while checking a condition. If it's not the top, climb one more step; if it is, stop.
That's why loops and conditions work together.
The condition decides whether to keep going, and the loop repeats the task.
Almost everything done "until it's finished" is built this way.
The effort a loop saves
Imagine writing the same task a hundred times by hand.
You'd have to write a hundred lines, and if one is wrong it's hard to find.
A loop is one line, "this, a hundred times," and that one line does a hundred lines' worth of work.
The same task 100 times, by hand vs with a loop. By hand, 100 lines; with a loop, 1 line.
That's the power of loops.
People get tired and make mistakes after writing something a hundred times.
Give a computer one line and it does it a hundred or ten thousand times, the same way, without tiring.
Many times, without tiring
Loops are a computer's greatest strength.
It does the same task quickly, identically, and without tiring.
Write it once for us, and it'll do it thousands of times.
In the next lesson we'll look at arrays, which hold many values together, and after that move on to functions, which bundle tasks under a name.
Now that you know repetition, what's next. Loop = write once, do many times → functions · collections · beyond.
We've now come as far as naming values (variables), knowing their types (data types), deciding (conditions), calculating (operators), and repeating (loops).
We've gathered almost all of a program's main skeleton.