How to loop in assembly language

10,709

Solution 1

You can make a loop like this:

mov ecx,12
your_label:
; your code
loop your_label

The loop instruction decrements ecx and jumps to the specified label unless ecx is equal to zero. You could also construct the same loop like this:

mov ecx,12
your_label:
; your code
dec ecx
jnz your_label

Solution 2

You determined that you need a for loop to achieve your goal, so maybe the C implementation of the for loop, in assembly, will help you:

Code Generation for For Loop

for (i=0; i < 100; i++)
{
  . . .
}

      * Data Register D2 is used to implement i.
      * Set D2 to zero (i=0)
      CLR.L D2

  L1  
      . . .
      * Increment i for (i++)
      ADDQ.L #1, D2
      * Check for the for loop exit condition ( i < 100)
      CMPI.L #100, D2
      * Branch to the beginning of for loop if less than flag is set
      BLT.S L1

SOURCE: eventhelix.com

Share:
10,709
TMan
Author by

TMan

Updated on November 21, 2022

Comments

  • TMan
    TMan over 1 year

    How would I calculate the first 12 values in the Fibonacci number sequence and be able to place it in EAX reg. and display calling DumpRegs? Using Indirect addressing I know I need a for loop here but I'm not sure how to even go about this. Any help or tips are appreciated.

          INCLUDE Irvine32.inc
    
    ; (insert symbol definitions here)
    
    .data
    
    ; (insert variables here)
       Fibonacci BYTE 1, 1, 10 DUP (?)
    
    .code
    main PROC
    
    ; (insert executable instructions here)
    
    
        ; (This below will show hexa contents of string.)
          mov   esi, OFFSET Fibonacci       ; offset the variables
          mov   ebx,1                   ; byte format
          mov   ecx, SIZEOF Fibonacci       ; counter
          call  dumpMem 
    
    
        exit        ; exit to operating system
    main ENDP
    
    ; (insert additional procedures here)
    
    END main
    
  • user786653
    user786653 over 12 years
    This looks like 68k assembler while the code in the OP (while not tagged as such) is x86.