Assembly Language - Loop Structures
Loops are one of the most common control structures in programs. In assembly language, you can use the LOOP instruction or conditional jumps to implement all kinds of loop logic.
The LOOP instruction
LOOP is an instruction designed by x86 specifically for loops; it uses ECX as the counter:
Each time LOOP is executed, ECX is decremented by 1 automatically, and if ECX is not 0 it jumps to the target label.
Example
; File path: loop_basic.asm
; Basic usage of the LOOP instruction: repeat the output 5 times
section
.data
msg
db
'runoob'
,
0xA
len
equ
$
msg
section
.text
global
_start
_start
:
mov
ecx
,
5
; Loop counter = 5 (loop 5 times)
repeat
:
; Save ecx (a system call may modify it)
push
ecx
; Output msg
mov
eax
,
4
mov
ebx
,
1
mov
ecx
,
msg
mov
edx
,
len
int
0x80
; Restore ecx
pop
ecx
loop
repeat
; ecx--; if ecx != 0 jump to repeat
mov
eax
,
1
mov
ebx
,
0
int
0x80
Running result:
$ nasm -f elf32 loop_basic.asm -o loop_basic.o
$ ld -m elf_i386 loop_basic.o -o loop_basic
$ ./loop_basic
runoob
runoob
runoob
runoob
runoob
loopBy default ECX (32-bit) is used as the counter. In 16-bit mode CX is used, and in 64-bit mode RCX. Be sure to set the value of ECX correctly before the loop.
Variants of LOOP
| Instruction | Jump condition | Description |
|---|---|---|
| LOOP | ECX != 0 | Standard loop: decrement ECX first, then test |
| LOOPE / LOOPZ | ECX != 0 and ZF = 1 | Continue the loop while equal |
| LOOPNE / LOOPNZ | ECX != 0 and ZF = 0 | Continue the loop while not equal |
Example
; LOOPE example: find the first non-zero value in an array
section
.data
array
db
0
,
0
,
0
,
5
,
0
,
0
; The first three are 0, the fourth is 5
section
.text
global
_start
_start
:
mov
ecx
,
6
; Array length
mov
esi
,
array
1
; Point to the position before the array
find_nonzero
:
inc
esi
; Move to the next element
cmp
byte
[
esi
]
,
0
; Current element == 0 ?
loope
find_nonzero
; If it is 0 and ecx > 0, continue the loop
; Loop ends: the first non-zero element was found, or the traversal finished
; esi now points to the address of the first non-zero element
; ecx holds the number of elements not yet compared
mov
eax
,
1
mov
ebx
,
0
int
0x80
Conditional loops (WHILE loops)
Implement a while loop with conditional jumps: test the condition first, then execute the loop body.
Example
; File path: while_loop.asm
; Implementation: while (x < 100) x = x * 2;
section
.data
x
dd
1
limit
dd
100
section
.text
global
_start
_start
:
; while loop
while_start
:
mov
eax
,
[
x
]
; Load x
cmp
eax
,
[
limit
]
; x < 100 ?
jge
while_end
; If x >= 100, end the loop
shl
eax
,
1
; x = x * 2
mov
[
x
]
,
eax
; Store x back
jmp
while_start
; Go back to the start of the loop and test again
while_end
:
; x is now 128 (1->2->4->8->16->32->64->128, stops at 128 >= 100)
mov
eax
,
1
mov
ebx
,
[
x
]
; Return x as the exit code
int
0x80
DO-WHILE loop
Execute the loop body first, then test the condition:
Example
; DO-WHILE loop: executes at least once
section
.data
counter
dd
0
section
.text
global
_start
_start
:
mov
dword
[
counter
]
,
0
do_loop
:
; Loop body: counter++ (executes at least once)
inc
dword
[
counter
]
; Test the condition
cmp
dword
[
counter
]
,
5
jl
do_loop
; counter < continue when < 5
; counter finally = 5
mov
eax
,
1
mov
ebx
,
0
int
0x80
Nested Loops
Nested loops need attention to saving the outer loop counter:
Example
; File path: nested_loop.asm
; Nested loop example: print a multiplication table (3×3)
section
.data
space
db
' '
newline
db
0xA
; Used to hold the converted digit characters (2 digits + space + null)
num_str
db
' '
,
0
section
.text
global
_start
_start
:
mov
ecx
,
3
; Outer loop counter (number of rows)
outer_loop
:
push
ecx
; ★ Save the outer loop counter! (Important)
mov
ecx
,
3
; Inner loop counter (number of columns)
inner_loop
:
push
ecx
; Save the inner loop counter
; Compute product = outer row number (4 - current ecx) × inner column number
; The specific number-conversion output is omitted here; only the structure is shown
; Actual output: row number × column number
pop
ecx
; Restore the inner loop counter
loop
inner_loop
; Inner loop
; Output a newline
mov
eax
,
4
mov
ebx
,
1
mov
ecx
,
newline
mov
edx
,
1
int
0x80
pop
ecx
; ★ Restore the outer loop counter
loop
outer_loop
; Outer loop
mov
eax
,
1
mov
ebx
,
0
int
0x80
The most common mistake in nested loops is forgetting to use the stack to save the value of the outer loop counter. LOOP modifies ECX, so when you reset ECX inside the inner loop, the outer count is lost. The solution is to push it onto the stack before entering the inner loop each time
push ecx, and pop it after leavingpop ecx.
Loop optimization techniques
Some ways to improve loop efficiency:
Example
; Comparison of loop optimizations
; Method A: use the LOOP instruction (slower, but not noticeably)
mov
ecx
,
1000
loop_a
:
add
eax
,
[
ebx
]
add
ebx
,
4
loop
loop_a
; Method B: use conditional jumps (manual counting) (usually faster)
mov
ecx
,
1000
loop_b
:
add
eax
,
[
ebx
]
add
ebx
,
4
dec
ecx
jnz
loop_b
; Method C: loop unrolling (fastest, but large code size)
; Unroll a 1000-iteration loop to process 4 elements per iteration
mov
ecx
,
250
; 1000 / 4 = 250
loop_unrolled
:
add
eax
,
[
ebx
]
add
eax
,
[
ebx
4
]
add
eax
,
[
ebx
8
]
add
eax
,
[
ebx
12
]
add
ebx
,
16
dec
ecx
jnz
loop_unrolled
; Method D: count down (reduces comparison instructions)
mov
ecx
,
1000
lea
ebx
,
[
array
1000
4
4
]
; Start from the end of the array
loop_reverse
:
add
eax
,
[
ebx
]
sub
ebx
,
4
dec
ecx
jnz
loop_reverse
Complete example: compute the sum of 1 to 100
Example
; File path: sum_1_to_100.asm
; Compute 1+2+...+100 = 5050
section
.data
msg
db
'Sum of 1 to 100 is: '
msg_len
equ
$
msg
newline
db
0xA
section
.bss
result_str
resb
12
; Hold the converted numeric string
section
.text
global
_start
_start
:
; Compute the accumulated sum
mov
ecx
,
100
; Loop 100 times
mov
eax
,
0
; The accumulated sum starts at 0
mov
ebx
,
1
; The number to add currently
sum_loop
:
add
eax
,
ebx
; eax += ebx
inc
ebx
; The next number
loop
sum_loop
; Continue the loop
; eax = 5050
; Output the prompt text
push
eax
; Save the result
mov
eax
,
4
mov
ebx
,
1
mov
ecx
,
msg
mov
edx
,
msg_len
int
0x80
pop
eax
; Restore the result
; Convert the number to a string (simple version: output the integer value directly)
; Simplified here: convert the low byte of eax into a character
add
al
,
'0'
; Not accurate, for demonstration only
mov
[
result_str
]
,
al
; Output the result
mov
eax
,
4
mov
ebx
,
1
mov
ecx
,
result_str
mov
edx
,
12
int
0x80
mov
eax
,
4
mov
ebx
,
1
mov
ecx
,
newline
mov
edx
,
1
int
0x80
mov
eax
,
1
mov
ebx
,
0
int
0x80
Converting numbers to strings is a common problem in assembly. The simple method above only works when the number is 0-9. The complete number-to-string algorithm will be explained in detail in the "Number Processing" chapter.