Implementing Loops in Assembly
What you'll learn: How to build for-loops and while-loops in assembly language using comparisons, decrements, and conditional jumps.
The Core Idea
In high-level languages, loops are built-in constructs like for and while. In assembly, you construct loops manually by combining three elements you've already learned:
- Comparison instructions (CMP) to test a condition
- Arithmetic instructions (DEC, ADD, SUB) to update loop counters
- Conditional jumps (JE, JNE, JL, etc.) to decide whether to repeat or exit
Think of it like building a racetrack: you create a label marking the start, execute your loop body, modify your counter, check if you should continue, and conditionally jump back to the label—or fall through to exit.
Building a Counting Loop
A typical for-loop that counts from 10 down to 1 looks like this in assembly:
MOV CX, 10 ; Initialize counter to 10
loop_start:
; ...loop body (your repeated work goes here)
DEC CX ; Decrease counter by 1
CMP CX, 0 ; Compare counter to zero
JNE loop_start ; Jump back if Not Equal (if CX ≠ 0)
The pattern: initialize → label → body → update → test → conditional jump back.
While-Loop Pattern
A while-loop tests before the body executes:
MOV AX, 0 ; Initialize condition variable
check_condition:
CMP AX, 100 ; Is AX < 100?
JGE done ; Jump if Greater or Equal (exit loop)
; ...loop body
ADD AX, 5 ; Update condition variable
JMP check_condition
done:
Here you test first, conditionally exit, run the body, then unconditionally jump back to test again.
Key Takeaway: Loops in assembly are hand-built using labels, comparison instructions, counter updates, and conditional jumps—giving you complete control over iteration logic at the hardware level.