Oria Gruber
Oria Gruber

Reputation: 1533

Counting zeros in an array assembly 8086

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

.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's not displaying the correct output. I'm expecting to see AX=4, but instead, when the program finished running I can see that AX=3.

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

Edit: Ok I correct the code, it does indeed give the desired outcome BUT...It still shows weird values for vec[di]. I still think I'm accessing it wrong and i got the correct result because of chance. I'd like someone to review it.

Upvotes: 3

Views: 3856

Answers (1)

amdn
amdn

Reputation: 11582

There are three problems, and many ways of improving your solution, I'll just mention the fixes:

  1. the first element of the array is at offset 0, not 1
  2. each element has a size of 2, not 1
  3. 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

should be

add di,2 ;case its not zero

and this line

cmp di,11

should be

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

That should get it working.

Upvotes: 4

Related Questions