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.
count = 0while count < 5 { print(count) count = count + 1}// Output: 0 1 2 3 4count starts at 0. Each iteration prints it, then increments. When count hits 5, the condition count < 5 flips to false and the loop stops.
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.
For Loops
A for loop crams three things into one line: initialisation, condition, update. Handy when you know exactly how many iterations you want.
for i = 0; i < 10; i = i + 1 { print(i)}This is exactly equivalent to writing:
i = 0while 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:
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.
do { password = prompt_user("Enter password:")} while password != correct_passwordIt 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.
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.
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:
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:
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 toploop_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
Registers
ALU
Memory
| Address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 10 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 20 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 30 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 40 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 50 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 60 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 70 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 80 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 90 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| A0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| B0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| C0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| D0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| E0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| F0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
Pipeline
Cycle 0Common 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.
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.