What is a loop in programming?
When you turn on “repeat one,” your music app plays the same song again instead of moving to the next track.
Write once, run again
A loop tells a computer when to repeat a set of instructions. The instructions inside are called the body. If the body says “draw a dot, then move right,” each trip through it adds another dot to a row.
Visit each item
A for loop can run its body once for each item in a list. Imagine a list of three colors: blue, yellow, pink. If the body draws a dot in the current color, the same instruction produces three different dots.
Check before repeating
A while loop checks a condition, a question with a true or false answer, before each trip through the body. Suppose the question is “Is there space for another dot?” If yes, draw one and check again. If no, skip the body and go on to the next instruction after the loop.
Watch what changes
Say there are three empty spaces. After each dot, the number of empty spaces drops by one, so the loop stops at zero. If the program keeps drawing over the first dot instead, space stays available; the loop never stops on its own. That is an infinite loop.
To understand a loop, ask two questions: What instructions run each time, and what decides whether they run again?
Questions students ask
Does a loop always run at least once?
No. A while loop skips its body if its condition is false at the first check. A for loop over an empty list has no items to visit, so it skips its body too.
How do I repeat something exactly ten times?
Use a for loop that counts through ten numbers. Its body runs once for each number.
Does everything after the loop repeat too?
No. Only the body repeats. Code after the loop waits until the loop finishes.
Check yourself
A for loop draws two dots for each of four colors. How many dots appear?
It draws eight dots because the two-dot instruction runs four times.
A loop draws while there is space, but the row starts full. How many dots does it add?
It adds none because the condition is false before the first dot.
A loop runs while a score is below five. If the score stays at two, will that check stop the loop?
No, because two stays below five every time the loop checks.

Snap your own page
Stuck on a page of your own? Take a photo and Slime makes it easy, without giving away the answer.
Snap your own pageMore topics
This topic in other languages: 한국어日本語
Written by Slime, an AI. It can be wrong: check with your textbook or teacher.