Doing the same thing many times
When you say "clap a hundred times," you don't write "clap" a hundred lines. "Clap, a hundred times" is enough. A loop is writing the same thing just once, and telling it to do it many times. It's what a computer does best.
A hundred lines vs one line
You want "clap"
done five times.
By hand,
you'd write "clap" five lines.
But with a loop,
"clap, five times"
is one line.
Below, compare the two.
Five lines by hand vs one loop line. (Same line five times · a loop is what·how many, one line)
Five you could still write.
But a hundred, a thousand?
By hand you can't.
A loop writes "what, how many"
just once.
The computer
repeats the rest on its own.
Counting as it repeats
A loop usually
runs while counting.
One, two, three…
until it reaches the set number,
it does the same thing.
Press the button below
and stamps appear one by one,
as many as set.
Repeat the same thing as many times as set. (The count rises one by one, a stamp each · stops at five)
Each count,
the same thing once.
This is the basics of a loop.
Set "how many times,"
and the computer, that many times,
repeats it the same,
without tiring.
Climbing to the top
Instead of a count,
sometimes you set "until when."
Like climbing stairs to the top,
"if not yet, one more."
This "not yet?"
is the condition from last time.
If true, do it again,
if false, stop.
Repeat while the condition is true. (At the top? if not, one more step · if so, stop)
So a loop and a condition
work together.
The condition decides "keep going or not,"
and the loop repeats the work.
Things done "until it's done"
are almost all
made this way.
The effort a loop saves
Say you write the same thing
a hundred times by hand.
A hundred lines,
and if one is wrong, it's hard to find.
A loop is one line.
"This, a hundred times."
One line does a hundred times' work.
The same thing 100 times, by hand vs loop. (100 lines by hand · 1 line by loop)
This is the power of a loop.
A person writing a hundred times
tires and errs.
But a computer,
given just one line,
does a hundred or ten thousand times
the same, without tiring.
A computer's greatest strength
A loop is
a computer's greatest strength.
The same thing, fast,
the same, without tiring.
Write it just once,
and it does it thousands of times.
Next we'll see how to bundle many things
and give them a name.
Once you know repeating, now. (A loop = write once, do many times → functions · collections · beyond)
Now we've named values (variables),
known their kinds (data types),
judged (conditions),
calculated (operators),
and reached repeating (loops).
We've gathered
almost the whole frame of a program.