Addition of 2-digit numbers using stack

428 Views Asked by At
model small
.stack 50
.data

msg db 10,13,"data is stored in  $"
msg1 db 10,13,"enter second number $"
num1 dw ?
num2 dw ?

.code
.startup

mov bl,0
mov ah,09
lea dx,msg
int 21h 
mov bx,0

read :
mov ah,01h       
;input number
int 21h    
cmp al,13      

je second       
mov cl,al
mov ch,0
sub cl,48    
converts ascii value
mov ax,10     

mul bx        

mov bx,ax 
add bx,cx
jmp read

second:
mov num1,bx
mov bx,0
mov ah,09h
mov dx,offset msg1
int 21h

read1:
mov ah,01h
int 21h
cmp al,13
je aedd
mov cl,al
mov ch,0
sub cl,48
mov ax,10
mul bx
add bx,cx

jmp read1

aedd:
add bx,num1

push '@'             

disp:


mov dx,ax
mov ax,bx
mov bx,dx
div bx
cmp ah,0
je poppy
push ax
jmp disp

poppy:

pop dx
cmp dx,'@'
je exit
mov ah,02h
int 21h

exit:
mov ah,04ch
mov al,0
int 21h
end

cmp al,13 is used to check whether the char is number or enter key.
Initially bx is 0.
push '@' is used to check end of stack.

I have taken single digit numbers and converted them to their place values. Then I have done their addition, put them on the stack and tried to display them. In some pc, it shows "divide overflow".

I don't know where I am wrong! Please help me with the logic.

2

There are 2 best solutions below

0
On

Problems

mov ax,10
mul bx
add bx,cx

jmp read1

When you get the second number you forget to actually put the product back in BX. You did this correctly when calculating the first number though.

mov ax,10
mul bx
mov bx,ax     <<<<<< Add this line
add bx,cx
jmp read1

disp:

mov dx,ax
mov ax,bx
mov bx,dx
div bx
cmp ah,0
je poppy
push ax
jmp disp

Here's a lot amiss:

  • You seem to be thinking that AX will hold 10 at the start of this snippet, but it will have the value 010Dh at this point!
  • A word sized division uses DX:AX as dividend. Since your number is just 1 word, you need to put it in AX and zero the high part in DX.
  • When you perform a word sized division the quotient will be in AX. Then you shouldn't check the AH register!
  • Since it's the remainder that needs to be pushed, it won't help writing push ax. Use push dx.
  • ...

Solution

You definitely should take a look at this recent post Displaying numbers with DOS.

You'll find there a perfect explanation of what you need to do.
It even uses the same technique of pushing some value on the stack to know where the number ends.

0
On

You have to clear the dx register before division that is why its causing division overflow.

 disp:       
       mov dx,ax
       mov ax,bx
       mov bx,dx
       mov dx, 0    <---- this has to be added 
       div bx
       cmp ah,0
       je poppy
        push ax
jmp disp