2

I took input in array. Then I tried to print the even numbers in the array. I got output as expected but I am getting extra numbers after printing the result. Like suppose my array is 1,2,3 output is

200000000000...

and continues.

My code:

include emu8086.inc

org 100h

define_scan_num
define_print_num
define_print_num_uns
.model small
.stack 100h
.data
a dw ?
b dw 50 dup(?)    
z dw ?

.code
main proc

mov ax, @data
mov ds,ax

call scan_num
printn ""

mov a,cx
mov bx,1

for1:
push cx
call scan_num
printn ""
mov b[bx],cx
add bx,2 
pop cx
loop for1

mov bx,1
mov cx,a  

for2:  
mov ax, b[bx]
mov dx,0
mov z,2
div z 
cmp dx,0  
je even
jne odd
loop for2

jmp skip

even:
mov ax,b[bx]
call print_num 
printn ""
add bx,2 
jmp for2

odd: 
add bx,2
jmp for2 

skip:
ret

main endp
end main
Sep Roland
  • 33,889
  • 7
  • 43
  • 76
Tapu Das
  • 391
  • 2
  • 17

1 Answers1

1
for2:  
mov ax, b[bx]
mov dx,0
mov z,2
div z 
cmp dx,0  
je even
jne odd
loop for2
jmp skip

The above code is a loop that is supposed to run a limited number of times.
It doesn't, because the externally placed even and odd cases jump back to the top of the loop when they should jump back to the loop for2 instruction for a correct loop execution.

Some why's and an example

  • Why do you divide by 2 to see if the number is even? It is enough to test the lowest bit. If that bit is 0 (jz) then the number is even, if that bit is 1 (jnz) then the number is odd.
  • Why do you place the even and odd cases external to the loop? It's much easier if you keep those inside the loop. Less jumping around.
  • Why do you duplicate code like add bx, 2 ? Seeing that is mostly an indication of ill-structured code.
  • Why do you start addressing your array of words at the odd offset of 1? If you decide to change this to the more sensible 0 then do it everywhere (in for1 and in for2)!

An example:

    xor     bx, bx       ; BX=0
    mov     cx, a
for2:  
    mov     ax, b[bx]
    test    ax, 1        ; TEST does not change the value in AX ...
    jnz     odd          ; print_num can use it without reloading!
even:
    call    print_num 
    printn ""
odd:
    add     bx, 2
    dec     cx
    jnz     for2
    ret
main endp
end main

For better performance you can replace loop ... by dec cx jnz ....

Sep Roland
  • 33,889
  • 7
  • 43
  • 76