Loops

Program Control Instructions like loops gives us control of the flow of a program.

Assembly like most languages is line-based, it will look to the following line for the next instruction. Contro instructions gives us the ability to change the flow of the program. Other types of control instructions are Branching and Function Calls.

Loop Structure

A loop is set of instructions that repeat for rxc times.

exampleLoop:
    instruction 1
    instruction 2
    instruction 3
    loop exampleLoop

Once the code reaches exampleLoop it will start executing the instructions under it. We can set the number of iterations in the rcx register. If the loop reaches the loop instruction it will decrease by 1. Before entering a loop, mov the number of loop iterations to the rcx register.

Instruction
Description
Example

mov rcx, x

Sets loop rxc counter to x

mov rcx, 3

loop

Back to start of loop until 0

loop exampleLoop

Example fibonacci

global  _start

section .text
_start:
    xor rax, rax    ; initialize rax to 0
    xor rbx, rbx    ; initialize rbx to 0
    inc rbx         ; increment rbx to 1
    mov rcx, 10     ; 10 iterations
loopFib:
    add rax, rbx    ; get the next number
    xchg rax, rbx   ; swap values
    loop loopFib

Fibonacci is the sum of the two preceding ones so: 0, 1, 1, 2, 3, 5, 8.

  • We store current num in rax and next num in rbx.

  • xor cleans register

  • inc rbx will run once to set rbx to 1

  • sum of rax and rbx

  • Swap rax with rbx.

  • Loop

Why swap rax with rbx? Swapping ensures that rbx always holds the previous Fibonacci number and rax holds the current one.

Step
rax value
rbx value
Description

Initialization

0

0

xor rax, rax and xor rbx, rbx

Increment

0

1

inc rbx (once)

Loop start

0

1

mov rcx, 10

1st iteration

1

1

add rax, rbx (0 + 1 = 1)

1

1

xchg rax, rbx (swap)

2nd iteration

2

1

add rax, rbx (1 + 1 = 2)

1

2

xchg rax, rbx (swap)

3rd iteration

3

2

add rax, rbx (1 + 2 = 3)

2

3

xchg rax, rbx (swap)

Last updated

Was this helpful?