Loops in assembly can be created using the loop instruction or by combining comparison and jump instructions.
loop Instruction
section .text
global _start
_start:
mov rcx, 5 ; Set loop counter to 5
loop_start:
; Your code here
dec rcx ; Decrement counter
jnz loop_start ; Jump to loop_start if rcx != 0
The loop instruction automatically decrements the rcx register and jumps if it is not zero.
section .bss
sum resb 1 ; Reserve 1 byte for the sum
section .text
global _start
_start:
mov rcx, 5 ; Loop counter
mov rax, 0 ; Initialize sum
loop_start:
add rax, rcx ; Add counter to sum
dec rcx ; Decrement counter
jnz loop_start ; Repeat until counter is 0
mov [sum], rax ; Store the result in sum
This program calculates the sum of numbers from 1 to 5.