Counting zeros in an 8086 array

I wrote this code to count the number of zeros in the vec array:

.model small
.stack 100h           
.data
    vec dw 1,2,0,3,0,4,5,6,0,0,5
    m1 dw 0
.code
    mov ax,@data
    mov ds,ax
    mov di,1 ;di is our running index
number_of_zeros:
    mov ax,vec[di]
    cmp ax,0
    je increment_m1 ;case its zero
    inc di;case its not zero
    cmp di,11
    jl number_of_zeros
    cmp di,11
    je end
increment_m1:
    inc m1
    inc di
    cmp di,11
    jl number_of_zeros
    cmp di,11
    je end
end:
    mov ax,m1

      

It doesn't display the correct output. I expect to see AX = 4, but instead, when the program is finished, I see AX = 3.

I think the problem has to do with the way I access the individual elements in the array. For some reason I can't figure it out, the first iteration says that vec [1] = 0200

Edit: Ok I'm fixing the code, it does indeed give the desired output, BUT ... It still shows weird values ​​for vec [di]. I still think I am accessing it the wrong way and I got the correct result due to chance. I would like someone to view it.

+3


source to share


1 answer


There are three problems and many ways to improve your solution, I just mentioned the fixes:

  • the first element of the array is offset 0

    , not1

  • each item is sized 2

    , not1

  • the comparison for the end condition needs to be updated (for reasons 1 and 2).

So this line

mov di,1 ;di is our running index

      

Should be

mov di,0 ;di is our running index

      

and this line

inc di;case its not zero

      



it should be

add di,2 ;case its not zero

      

and this line

cmp di,11

      

it should be

cmp di,20 ; last element is at offset sizeof(dw) * (num_elements-1) = 2 * (11-1) = 20

      

This should make it work.

+4


source







All Articles