ShadowViper
ShadowViper

Reputation: 365

For Loops and Transversing through arrays in x86 Assembly Code

I am trying to create a program using x86 Assembly (TASM) that transverses through 2 sets of arrays and does a basic addition between the two arrays using a for loop. However, i have never used a for loop or an array in assembly, so im quite confused on how i would go about implementing it.

so let say i have this pusodo code:

for i := 0 to n-1 do
        s := a[ i] + b[ i]; 
        ...
endfor;

An this is my code so far which takes the array a and b in si and di respectively and the size n in cx, how would i implement the above pusodo code in my code?

m   dw  ?
s   dw  ?


    .code

    extrn   putint: proc

    public  maxp_ip

maxp_ip proc ;(n)

; computes the max-plus inner product between two vectors a and b of length n
; input: CX = n
;        SI = a
;        DI = b  
; output: AX = m

; save regs
    push si
    push di 
    push ax ; assigned to m
    push bx ; assigned to s
    push cx 

; m := -32768   
    mov m, -32768

; for i := 0 to n-1 do

Note that the above code isnt my entire code, just the part where i want to implement the for loop and addition. Also, could you please explain how I would do this, with sample code (I am a visual learner, so i need to see how to do it, sorry). Thanks.

Upvotes: 2

Views: 12897

Answers (1)

Next is the code you want. Made with EMU8086, just copy, paste and run:

.stack 100h
.data

array1 dw 2,4,6,8,10,12,14,16,18
array2 dw 2,3,5,7,11,13,17,19,23

.code          
;INITILIZE DATA SEGMENT.
  mov  ax,@data
  mov  ds,ax

;SUM ARRAY ELEMENTS.                              
  mov  si, offset array1
  mov  di, offset array2
  mov  cx, 9 ;LENGHT OF ARRAYS.
for:
  mov  ax, [ si ]
  mov  bx, [ di ]
  add  ax, bx ;SUM BOTH ELEMENTS.
  ;HERE WE DO SOMETHING WITH THE SUM, LIKE DISPLAY IT.
  add  si, 2 ;NEXT ELEMENT OF ARRAY 1 (DW = 2 BYTES).
  add  di, 2 ;NEXT ELEMENT OF ARRAY 2 (DW = 2 BYTES).
  loop for ;DECREASE CX. JUMP IF NOT ZERO.

;FINISH THE PROGRAM PROPERLY.
  mov  ax,4c00h
  int  21h           

It walks on every element of the arrays, adding every pair of elements into AX. Notice CX is been used as a reverse counter (from 9 to 0), but the arrays elements are visited from 0 to 8. Both pointers to arrays, SI and DI, are increased by 2 because both arrays are of type DW (two bytes long).

You can play with the pointers to change the order you visit the arrays elements. For example :

mov  di, offset array2 + 8
...
dec  di, 2 ;PREVIOUS ELEMENT OF ARRAY 2 (DW = 2 BYTES).

This way you can sum the elements of array 1 in order with the elements of array 2 in reverse order.

Hope it helps.

Upvotes: 3

Related Questions