Blog post
Algorithmic Thinking, Part 1: Loops Are the Repeat Button for Code
Loops are the mechanism that turns 'do this once' into 'do this n times' — the series that ends at graphs and depth-first search starts here.
- Category
- algorithms
- Published
This is post 1 of a 13-part series that goes: loops → conditionals → variables → conditionals synthesis → path logic → nested loops → permutations → Big O → recursion → maze navigation → depth-first search → graphs → tables. Each post builds on the last; by the end you'll have everything needed to write a maze-solving DFS from scratch. Start here.
What a loop actually does
A computer only ever executes one instruction at a time, in order. A loop is the construct that says: "before moving on, come back and do this block again — and again — until some condition says stop." Everything else about loops is detail on top of that one idea.
The three shapes
Counted (for) — you know in advance how many times to repeat:
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Rep {i}");
}
i is the loop variable, i < 5 is the condition checked before each iteration, and i++ runs after each iteration. All three live in the for header so the repeat logic stays in one place instead of scattered across the function.
Conditional (while) — you don't know the count, only the stopping condition:
int remaining = LoadQueue().Count;
while (remaining > 0)
{
remaining = ProcessNext();
}
Use while when the number of iterations depends on runtime state — a queue draining, a search converging, a socket streaming until it closes.
Collection (foreach) — you have a sequence and want each element, and you don't care about the index:
foreach (var order in orders)
{
Ship(order);
}
foreach is a for loop with the indexing and bounds-checking done for you. Reach for it first; drop to for only when you genuinely need the index or need to skip/step non-sequentially.
The bug that loops are famous for
Off-by-one errors come from a mismatch between the condition you wrote and the range you meant:
for (int i = 0; i <= items.Length; i++) // bug: should be <
{
Console.WriteLine(items[i]); // throws on the last iteration
}
items.Length is a valid count, not a valid index — indexes run from 0 to Length - 1. The fix is mechanical once you internalize it: strict < when counting up to a length, <= when counting up to a maximum inclusive value you actually intend to hit.
Why this is where an algorithms series starts
Every technique later in this series is a loop wearing a costume. A search is a loop that stops early. Recursion (post 9) is a loop where the "come back and repeat" happens via the call stack instead of a for header. Depth-first search (post 11) is a loop over a graph's neighbors that recurses. Get comfortable with "repeat until a condition holds" now, and the rest of the series is mostly about what you're repeating over, not new ways of repeating.
Next: Conditionals — how a loop decides, mid-repetition, to behave differently.