4.4. Loops
Table of Contents
Why Loops Matter
In programming you very often need to repeat something:
- Check every item in a list
- Keep asking the user for input until it is valid
- Process rows in a file or records from a database
- Wait for some condition to become true
You could copy and paste the same line of code many times, but that would be:
- Hard to read
- Hard to change
- Very easy to break
Loops let you repeat a block of code automatically. You write the logic once, and the loop runs it many times.
Key idea: A loop repeats a block of code while a condition is true or for each item in a sequence.
In this chapter, we focus on the concepts that are the same in most languages. In later chapters, you will see how loops look in specific languages such as Python.
Two Main Types of Loops
Most popular languages give you two big families of loops:
- Counted / “for” style loops
Repeat a known number of times or go over a sequence. - Conditional / “while” style loops
Repeat as long as some condition is true.
Different languages have different syntax, but the ideas are very similar.
Here is some language‑agnostic pseudocode that shows both styles:
# for / counted loop
for i from 1 to 5:
print(i)
# while / conditional loop
x = 1
while x <= 5:
print(x)
x = x + 1Both snippets print the numbers 1 to 5, but work in slightly different ways.
For Loops: Repeating a Known Number of Times
A for loop is usually used when you either:
- Know exactly how many times to repeat, or
- Want to go through every item in a collection (list, array, etc).
Typical shape in pseudocode:
for counter from START to END:
# loop bodyExample: Print Numbers 1 to 10
for i from 1 to 10:
print(i)This:
- Starts
iat 1 - Runs the loop body
- Increases
iby 1 - Stops after
ireaches 10
You do not have to manually update i inside the loop. The loop does that automatically.
Example: Repeat an Action N Times
Sometimes you just want to repeat something N times, and do not care about the counter value itself.
for _ from 1 to 3:
print("Connecting to server...")
This prints the message 3 times. The underscore _ is often used to say: “I do not care about this variable.”
Example: Looping Over a List
For loops are very often used to visit each element in a list or array.
users = ["alice", "bob", "charlie"]
for user in users:
print("Sending email to " + user)You do not care about the index positions here. You just care about the values.
While Loops: Repeat While a Condition Is True
A while loop repeats as long as some condition is true.
Pseudocode shape:
while CONDITION:
# loop bodyIf the condition starts out false, the body might not run even once.
Example: Count Until a Limit
count = 0
while count < 5:
print("Count is " + to_string(count))
count = count + 1Flow:
- Check
count < 5 - If true, run the body
- Update
count - Go back to step 1
When count becomes 5, count < 5 is false, so the loop stops.
Example: Ask Until Input Is Valid
While loops are great when you do not know in advance how many times you must repeat.
password = ""
while password != "secret123":
password = read_line("Enter password: ")
print("Access granted")If the user types the wrong password 10 times, the loop runs 10 times. If they type it correctly the first time, the loop runs only once.
Loop Control: break and continue
Inside loops you sometimes want to:
- Stop the loop early
- Skip the rest of the current iteration and go to the next one
Almost every language gives you two important keywords for this.
break: Exit the Loop Early
break jumps out of the loop completely.
numbers = [3, 7, 2, 9, 5]
target = 9
for n in numbers:
if n == target:
print("Found it!")
break
print("Loop finished")- When
nis 9, it prints "Found it!" andbreakexits the loop. - The loop will not check 5 at all.
This is very useful when searching and you can stop as soon as you find what you want.
continue: Skip to the Next Iteration
continue stops the current iteration and moves to the next one, but does not exit the loop entirely.
numbers = [1, 2, 3, 4, 5, 6]
for n in numbers:
if n % 2 == 0:
continue
print(n)Explanation:
- For even numbers, the
continueruns and skipsprint(n). - Only odd numbers 1, 3, 5 are printed.
Combining with While Loops
break and continue also work with while loops.
while true:
value = read_line("Enter a number (or 'q' to quit): ")
if value == "q":
break # exit loop
if value == "":
continue # skip empty input and ask again
print("You entered: " + value)breakends the loop if user typesq.continueskips the rest of the body when input is empty.
Infinite Loops: What to Avoid
An infinite loop is a loop that never stops. Sometimes they are intentional, for example a web server that runs forever until it is shut down. Often, they are bugs.
Rule: Every loop should have a clear path where its condition becomes false or it hits a break. If not, you risk an infinite loop.
Example: Bad Infinite While Loop
count = 0
while count < 5:
print(count)
# Oops, forgot to update count
count never changes, so count < 5 is always true. The loop never ends.
To fix it:
count = 0
while count < 5:
print(count)
count = count + 1Example: Intentional Infinite Loop with Break
From time to time, intentional infinite loops can be useful.
while true:
command = read_line("Command: ")
if command == "quit":
print("Goodbye")
break
handle(command)
Here the loop is designed to run until the user enters "quit". The stopping condition is inside the loop body as a break.
Looping Over Collections
A collection can be:
- A list or array
- A dictionary or map
- A set
- Records from a database query
- Lines in a file
Most backend code processes collections all the time. You must be comfortable looping over them.
Lists / Arrays
Basic examples, in pseudocode:
emails = ["a@example.com", "b@example.com", "c@example.com"]
for email in emails:
print("Sending to " + email)With index:
for index from 0 to length(emails) - 1:
print("Email " + to_string(index) + ": " + emails[index])Some languages let you get both index and value in one loop.
Dictionaries / Maps
Dictionaries hold key-value pairs.
user = {
"id": 1,
"name": "Alice",
"role": "admin"
}
for key, value in user:
print(key + " = " + to_string(value))This might print:
id = 1
name = Alice
role = adminYou can also loop only over keys or only over values, depending on the language.
Nested Loops
You can put a loop inside another loop. This is called a nested loop.
Example: print all possible combinations of sizes and colors.
sizes = ["S", "M", "L"]
colors = ["red", "green", "blue"]
for size in sizes:
for color in colors:
print("Product " + size + " in " + color)Output:
Product S in red
Product S in green
Product S in blue
Product M in red
...
Product L in blueNested loops are powerful, but they can also be slow if each list is large. In backend development, you will often look for ways to avoid very deep or very large nested loops when performance matters.
Common Loop Patterns in Backend Code
Here are patterns you will see all the time in backend development, written in generic pseudocode.
Process Each Record
Example: log each order in a list of orders.
for order in orders:
print("Order #" + to_string(order.id) + " total: " + to_string(order.total))Find the First Match
Example: find first user with admin role.
admin_user = null
for user in users:
if user.role == "admin":
admin_user = user
break
if admin_user != null:
print("Admin is " + admin_user.name)
else:
print("No admin found")Filter Items
Example: collect only active users.
active_users = []
for user in users:
if user.is_active:
active_users.append(user)Later on, in real languages, you will also see more compact syntax for this kind of operation, but the core idea is always looping and choosing what to keep.
Accumulate a Total
Example: sum up order totals.
total_revenue = 0
for order in orders:
total_revenue = total_revenue + order.total
print("Total revenue: " + to_string(total_revenue))This pattern is called a reduction or fold. Many higher-level tools are built on top of this idea, but under the hood they still loop.
Off-by-One Errors
A very common loop bug is the off-by-one error. This means your loop runs one time too many or one time too few.
This often happens when you are using indexes and lengths.
Imagine a list with 5 elements. Valid indexes are 0, 1, 2, 3, 4.
You want to visit all of them.
Bad version:
for i from 0 to length(list):
print(list[i])
If length(list) is 5, the last iteration tries to access list[5], which does not exist.
Correct version:
for i from 0 to length(list) - 1:
print(list[i])Or, if the language allows:
for item in list:
print(item)This avoids indexing completely.
Rule: When using indexes, make sure your highest index is length - 1, not length.
Choosing the Right Loop
You will often have a choice between for and while. Here are some guidelines.
| Situation | Use | Reason |
|---|---|---|
| You know exactly how many times to repeat | for | Clear and concise |
| You loop over each item in a collection | for | Expresses “for each item” directly |
| You repeat until a condition changes | while | Condition is the main thing that controls the loop |
| You build a server that runs until shutdown | while (true) + break | Condition may depend on signals or events |
| You are indexing into a list by position | for (index style) | Easier to see start and end indexes |
In practice, prefer for loops when possible, especially when dealing with lists or other collections. They are usually less error-prone.
Summary
You now know the core loop concepts that appear in almost every programming language:
- For loops to repeat a fixed number of times or to go through items in a collection.
- While loops to repeat while a condition remains true.
- break to exit a loop early and continue to skip to the next iteration.
- The danger of infinite loops when the condition never becomes false.
- How to loop over lists, dictionaries, and nested collections.
- How loops are used in typical backend tasks like processing records, searching, filtering, and accumulating totals.
- How to watch out for off-by-one errors, especially with indexes.
In the next chapters and in later language-specific sections, you will see how these ideas look in real code, for example with Python syntax. The concepts here, however, stay the same across almost every programming language you will use for backend development.
Views: 7
KAHIBARO