KAHIBARO
Discord Login Register

4.4. Loops

Why Loops Matter

In programming you very often need to repeat something:

You could copy and paste the same line of code many times, but that would be:

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:

Different languages have different syntax, but the ideas are very similar.

Here is some language‑agnostic pseudocode that shows both styles:

text
# for / counted loop
for i from 1 to 5:
    print(i)
# while / conditional loop
x = 1
while x <= 5:
    print(x)
    x = x + 1

Both 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:

  1. Know exactly how many times to repeat, or
  2. Want to go through every item in a collection (list, array, etc).

Typical shape in pseudocode:

text
for counter from START to END:
    # loop body

Example: Print Numbers 1 to 10

text
for i from 1 to 10:
    print(i)

This:

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.

text
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.

text
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:

text
while CONDITION:
    # loop body

If the condition starts out false, the body might not run even once.

Example: Count Until a Limit

text
count = 0
while count < 5:
    print("Count is " + to_string(count))
    count = count + 1

Flow:

  1. Check count < 5
  2. If true, run the body
  3. Update count
  4. 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.

text
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:

Almost every language gives you two important keywords for this.

break: Exit the Loop Early

break jumps out of the loop completely.

text
numbers = [3, 7, 2, 9, 5]
target = 9
for n in numbers:
    if n == target:
        print("Found it!")
        break
print("Loop finished")

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.

text
numbers = [1, 2, 3, 4, 5, 6]
for n in numbers:
    if n % 2 == 0:
        continue
    print(n)

Explanation:

Combining with While Loops

break and continue also work with while loops.

text
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)

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

text
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:

text
count = 0
while count < 5:
    print(count)
    count = count + 1

Example: Intentional Infinite Loop with Break

From time to time, intentional infinite loops can be useful.

text
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:

Most backend code processes collections all the time. You must be comfortable looping over them.

Lists / Arrays

Basic examples, in pseudocode:

text
emails = ["a@example.com", "b@example.com", "c@example.com"]
for email in emails:
    print("Sending to " + email)

With index:

text
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.

text
user = {
    "id": 1,
    "name": "Alice",
    "role": "admin"
}
for key, value in user:
    print(key + " = " + to_string(value))

This might print:

text
id = 1
name = Alice
role = admin

You 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.

text
sizes = ["S", "M", "L"]
colors = ["red", "green", "blue"]
for size in sizes:
    for color in colors:
        print("Product " + size + " in " + color)

Output:

text
Product S in red
Product S in green
Product S in blue
Product M in red
...
Product L in blue

Nested 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.

text
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.

text
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.

text
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.

text
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:

text
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:

text
for i from 0 to length(list) - 1:
    print(list[i])

Or, if the language allows:

text
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.

SituationUseReason
You know exactly how many times to repeatforClear and concise
You loop over each item in a collectionforExpresses “for each item” directly
You repeat until a condition changeswhileCondition is the main thing that controls the loop
You build a server that runs until shutdownwhile (true) + breakCondition may depend on signals or events
You are indexing into a list by positionfor (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:

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

Comments

Please login to add a comment.

Don't have an account? Register now!