how-to-do-addition-and-subtraction-in-assembly-language

 assembly-language-math-operations-addition-subtraction

code:

.model small
.stack 100h
;for defining varaiable
.data 
a db 'Enter the first number:$'
b db 'Enter the secont number:$'
c db 'add: $'
d db 'sub: $'

.code 
main proc
    mov ax,@data ;initialize data segment
    mov ds,ax ;move to the data segment register
    
    
    ;print first string
    mov ah,9
    lea dx,a  ;it loads the address of a variable or memory location into a register. 
    int 21h
    
    ;input first number from the user
    mov ah,1
    int 21h
    mov bl,al
    ;Backup  first user input for subtract part
    mov bh,bl
    
    ;for new line
    mov ah,2
    mov dl,10
    int 21h
    mov dl,13 
    int 21h
           
    ;print the second string
    mov ah,9
    lea dx,b
    int 21h
    
    ;input secont number from the user
    mov ah,1
    int 21h
    mov cl,al
    ;Backup  second user input for subtract part
    mov ch,cl
    
 
    ;for new line
    mov ah,2
    mov dl,10
    int 21h
    mov dl,13 
    int 21h
    
    
    ;--------adding part---------
    ;for print result string
    mov ah,9
    lea dx,c
    int 21h
    
    ;for add
    add bl,cl    
    
    ;convert ascii for display
    sub bl,48   
    
    ;for print
    mov ah,2
    mov dl,bl
    int 21h
     
    ;-------subtract part--------
    
    ;for new line
    mov ah,2
    mov dl,10
    int 21h
    mov dl,13 
    int 21h
            
            
    ;print result string
    mov ah,9
    lea dx,d
    int 21h
    
    ;restore orginal input from backup
    mov bl,bh
    mov cl,ch  
    
    ;subtract
    sub bl,cl
    ;check if result is negative
    js negative_result ;jump if sign sf = 0 positive, sf=1 negative
    
    ;if rusult is positive
    add bl,48 ;convert to ascii for display
    ;for print sub result
    mov ah,2
    mov dl,bl
    int 21h
    jmp done
    
    negative_result:
    neg bl ;make the result positive
    add bl,48 ;convert to ascii for display
    mov ah,2
    mov dl,'-' 
    int 21h
    mov dl,bl ;print the number
    int 21h
    
    done:
    
    exit:
    mov ah,4ch
    int 21h
    main endp
end main
    
    result:

    

No comments

Theme images by hdoddema. Powered by Blogger.