What is a loop?
A loop is a way for a computer to repeat the same steps again and again until something tells it to stop. It is like telling a robot: "Do this task 5 times" or "Keep doing this until I say stop."
Common types of loops
-
1) For loop (counting loop)
Use when you know how many times you want to repeat something (for example, 5 times).
for i from 1 to 5: print('Hello', i)This will print Hello 1, Hello 2, ... Hello 5.
-
2) While loop (condition loop)
Use when you want to repeat as long as a condition is true. The condition is checked before each repeat.
count = 1 while count <= 5: print('Hi', count) count = count + 1This also prints Hi 1 through Hi 5.
-
3) Do-while loop (do then check)
Some languages have a loop that always runs the block at least once, then checks the condition to decide whether to repeat.
do { print('Hey') count = count + 1 } while (count <= 5)This will run the block, then check if it should run again.
-
4) For-each loop (loop over items)
Use when you want to do something to every item in a list, array, or collection.
for fruit in ['apple', 'banana', 'cherry']: print(fruit)This prints each fruit in the list, one by one.
Other important loop ideas
-
Nested loops
A nested loop is a loop inside another loop. Use when you need to repeat a set of steps for each item of another set (for example, rows and columns).
for row from 1 to 3: for col from 1 to 2: print('cell', row, col)This prints cell positions like (1,1), (1,2), (2,1), ...
-
Infinite loops
An infinite loop never stops by itself. Example:
while True:in Python. Infinite loops are usually a bug unless you really want the program to run forever (like a game loop). You must include a way to stop it.while True: do_something() if user_wants_to_stop: break -
Break and continue
These commands change loop behavior:
- break: stops the whole loop right away.
- continue: skips the rest of the current loop repeat and moves to the next one.
for i from 1 to 10: if i == 5: break # stops the loop when i is 5 for i from 1 to 10: if i % 2 == 0: continue # skips even numbers
Quick tips
- Choose a for loop when you know how many repeats you want.
- Choose a while loop when you repeat until a condition changes.
- Watch out for infinite loops. Make sure the condition will eventually become false or include a break.
- Use nested loops carefully — they can make programs slow if they run many times.
Try these practice tasks
- Write a loop that prints numbers 1 to 10.
- Write a loop that prints only even numbers from 2 to 20.
- Use a nested loop to print a 3 by 3 grid of stars (*) like a small square.
If you want, tell me which programming language you are using (like Python, Scratch, or JavaScript) and I will give you exact code examples for that language.