Search code examples
loopsassemblymasmirvine32

Conditional in Loop MASM x86 Assembly


I am using the Irvine library.

I want to iterate through a DWORD array while checking if each value is in the range of j and k. The code I have does not work currently. Here is what I have:

INCLUDE Irvine32.inc
COMMENT !
.386
.model flat, stdcall
.stack 4096

ExitProcess PROTO, code:DWORD
DumpRegs PROTO
!

.data
myArr DWORD 1h,2h,3h,4h
prompt BYTE "Enter the value for j and k: ", 0
counter BYTE ?

.code
MAIN PROC
  mov eax, 0              ;    sum

  ; Get user vals for j and k
  mov edx, OFFSET prompt
  CALL WriteString
  CALL ReadInt
  mov ebx, eax

  CALL ReadInt
  mov edx, eax



  CALL sumArr             ; Call #1  *****

  mov ebx, 5              ;   j = 5
  mov edx, 8              ;   k = 8

  CALL sumArr             ; Call #2  *****


Main endP



sumArr PROC USES esi ecx edx ebx
    mov counter, LENGTHOF myArr
    mov esi, OFFSET myArr   ;    location pointer
    mov ecx, LENGTHOF myArr ;    size


    getArr:
      cmp ebx, [esi]
      jae aboveEqual
      add esi, TYPE myArr


    aboveEqual:
      cmp edx, [esi]
      jbe inRange

    inRange:
      add eax, [esi]

      LOOP getArr
    CALL DumpRegs
    RET
sumArr ENDP

I want to be able to do a comparison for each element in the array. How can I do this?


Solution

  • You forgot to zero EAX in SUMARR.
    Both cmp ebx,[esi] and cmp edx,[esi] must have source and destination operands switched place.
    Move add esi, TYPE myArr right before the LOOP instruction.
    If the conditional jumps are not taken then unconditionally jump to the add esi, TYPE myArr instruction.

    In mov ecx, LENGTHOF myArr will the immediate be 4 or will it be 16?