Skip to main content
Be Bitwise

Loops: Repeating Work

Functions & Control Flow · Coding Fundamentals track

6 min read

In this module

Doing Things More Than Once

Programs are forever repeating work. Process every item in a list. Check a condition every second. Hammer at a server until it answers. Without loops, you'd be copy-pasting the same code for every repetition — and you wouldn't even know up front how many times to paste it.

A loop is a control-flow structure that re-runs a block of code as long as a condition holds (or for some specified number of iterations).

While Loops

The while loop is the most fundamental loop. It checks a condition before each iteration; if the condition holds, the body runs. Then the condition is checked again, and again, until it fails.

text
count = 0
while count < 5 {
print(count)
count = count + 1
}
// Output: 0 1 2 3 4

count starts at 0. Each iteration prints it, then increments. When count hits 5, the condition count < 5 flips to false and the loop stops.

Key Concept

A while loop checks its condition before each iteration. If the condition is false on the first check, the body never runs at all. If the condition never falls to false, you've got an infinite loop.

Try itChange the upper bound and see the loop adapt.
C (GCC 9.2.0)

For Loops

A for loop crams three things into one line: initialisation, condition, update. Handy when you know exactly how many iterations you want.

text
for i = 0; i < 10; i = i + 1 {
print(i)
}

This is exactly equivalent to writing:

text
i = 0
while i < 10 {
print(i)
i = i + 1
}

Plenty of modern languages also ship a for-each loop (or for-in) that iterates directly over the elements of a collection:

text
names = ["Alice", "Bob", "Charlie"]
for name in names {
print("Hello, " + name)
}

Reach for this one when you care about the elements themselves rather than the index.

Do-While: Guaranteed First Execution

Sometimes you want the body to run at least once no matter what. A do-while loop puts the condition check after the body, not before.

text
do {
password = prompt_user("Enter password:")
} while password != correct_password

It always prompts at least once and keeps prompting until the user types the right password. With a plain while loop, you'd have to seed password ahead of time with some value you know is wrong.

Infinite Loops and Breaking Out

An infinite loop runs forever. Sometimes that's the goal — a game loop, a server waiting on connections, the OS idle loop.

text
while true {
event = wait_for_event()
handle(event)
}

To bail out of a loop early, most languages give you break. To skip the rest of the current iteration and jump to the next one, there's continue.

text
for i = 0; i < 100; i = i + 1 {
if i == 50 {
break // stop the entire loop at 50
}
if i % 2 == 0 {
continue // skip even numbers, jump to next iteration
}
print(i) // only prints odd numbers less than 50
}

Nested Loops

Loops can hold other loops. The classic case is walking a two-dimensional structure like a grid or a table:

text
for row = 0; row < 3; row = row + 1 {
for col = 0; col < 3; col = col + 1 {
print("(" + row + "," + col + ")")
}
}
// Output: (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)

Watch out with nested loops — the iteration count multiplies. A 1000-iteration loop inside another 1000-iteration loop gives you a million iterations. That intuition feeds straight into algorithmic complexity, which you'll get to soon.

How Loops Work at the Machine Level

At the CPU level, a loop is just a conditional branch that jumps backward. A while loop in (simplified, pseudo-) assembly looks something like this:

asm
loop_start:
CMP count, 5 ; check condition
BGE loop_end ; if count >= 5, jump past the loop
; ... loop body ...
ADD count, count, 1 ; increment
JMP loop_start ; jump back to the top
loop_end:

Every iteration costs a comparison, a conditional branch, the body, an unconditional jump back, and the comparison once more. Modern CPUs optimise this aggressively with branch prediction and loop unrolling, but the underlying mechanism never changes — compare, branch, execute, jump back.

The simulator below runs that shape on a small teaching CPU. It has no "branch if greater or equal", so the loop tests for equality instead: it adds count to a running total in R1 while count (R0) goes 0, 1, 2, 3, 4, and leaves when count hits 5. Step through it and watch the PC jump backwards at JUMP loop_start, once per iteration, and forwards past the body when JZ finally fires. R1 should end on 0 + 1 + 2 + 3 + 4 = 10.

For the best simulation experience, use a desktop browser.

Assembly

200ms

Registers

R00
0x0000
R10
0x0000
R20
0x0000
R30
0x0000
R40
0x0000
R50
0x0000
R60
0x0000
R70
0x0000
PC0
0x0000
SP255
0x00FF
FLAGS0x00
ZCVN

ALU

Idle

Memory

PCSPWatched
Memory contents — rows indexed by base address, columns by hex offset
Address0123456789ABCDEF
0000000000000000000000000000000000
1000000000000000000000000000000000
2000000000000000000000000000000000
3000000000000000000000000000000000
4000000000000000000000000000000000
5000000000000000000000000000000000
6000000000000000000000000000000000
7000000000000000000000000000000000
8000000000000000000000000000000000
9000000000000000000000000000000000
A000000000000000000000000000000000
B000000000000000000000000000000000
C000000000000000000000000000000000
D000000000000000000000000000000000
E000000000000000000000000000000000
F000000000000000000000000000000000

Pipeline

Cycle 0
Fetch
Decode
Execute
Writeback
→
→
→
No instruction loaded

Common Loop Pitfalls

Off-by-one errors are the most common loop bugs. < when you meant <=, or starting at 1 instead of 0, and your loop fires one too many or one too few times. These subtle slip-ups are behind a startling share of software bugs.

Both functions below are meant to add up the five readings. Predict what each prints before you run it, then fix the loop conditions.

Try itOne loop skips the first reading and the other skips the last. Fix both so they print 150.
C (GCC 9.2.0)

The opposite mistake, i <= N, reads one element past the end of the array. C won't stop you; it just reads whatever sits next in memory, which is how many buffer overflows begin.

Forgetting to update the loop variable creates an infinite loop — the condition never moves, so the loop never stops. Always make sure something inside the body is dragging you toward the exit condition.