Search code examples
arraysassemblysumtasmemu8086

finding the lowest value of an array while adding them in assembly


I am learning assembly and recently moved to signed numbers topic. In one of the exercises I stuck. There is an array array DB +53, -87, -45, +23, -79, +28, -90, +75, -39 and I want to find the lowest value while adding them. for ex:

let lowest value = 0

in first 2 iterations --> 53+(-87) = -34 becomes lowest. -34 +(-45) = -79 becomes lowes etc. I tried to implement a loop but since I have overflows the code couldn't handle. Any help is appreciated.


Solution

  • Given that the array is defined to contain signed bytes, it's tempting to work with byte-sized registers. This could rapidly produce overflow. Therefore it's better to work with word-sized registers. All it takes is sign-extending the byte value from AL into AXusing the CBW instruction.

      mov si, 9             ; Number of elements
      xor dx, dx            ; Sum
      mov cx, 32767         ; Current lowest
      mov bx, offset array  ; Address of array
    again:
      mov al, [bx]          ; Fetch next byte element
      cbw                   ; Sign-extend to word
      add dx, ax            ; Add to the sum
      cmp dx, cx            ; Is it less (signed comparison) ?
      jnl NotLess
      mov cx, dx            ; Only replace if less than previous lowest
    NotLess:
      inc bx                ; To next byte element
      dec si
      jnz Again
    

    The CX register (-197) has the LowestValueWhileAdding.
    The DX register (-161) has the Sum.