w1coding.comAll tutorials

Assembly Loops

Assembly lessons
  1. Environment Setup
  2. Introduction
  3. Syntax
  4. Datamovement
  5. Operators
  6. Control
  7. Loops
  8. Interupts
  9. Functions
  10. Memory
  11. System
  12. Debugging
  13. Macros
  14. Execution
  15. Floating
  16. Interupts
  17. Optimization
  18. Linking
  19. Inline
  20. Registers
  21. Bootloader
  22. Macros
  23. Stack
  24. Call
  25. Technique
  26. Responsive

Loops in Assembly

Loops in assembly can be created using the loop instruction or by combining comparison and jump instructions.

Using the 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.

Example: Adding Numbers in a Loop

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.