Thursday, December 11, 2008

Add, Subtract, Divide, Multiply in Assemble

.model small
.stack 256h
CR equ 13
dlf equ 10
dA equ 'A'
S equ 'S'
.data
addition db CR,LF,'[A] add$'
subtraction db CR,LF,'[S] subtract$'
multiplication db CR,LF,'[M] muliply$'
division db CR,LF,'[D] divide$'
msg db CR, LF, 'Enter your choice:$'
msg1 db CR, LF, 'Enter first number:$'
msg2 db CR, LF, 'Enter the second number:$'
num db CR, LF, 'The answer is:$'
num1 dw ?num2 dw ?
.code
start:
mov ax, @data
mov ds, ax
mov ax, offset addition
call put_string
mov ax, offset subtraction
call put_string
mov ax, offset multiplication
call put_string
mov ax, offset division
call put_string
mov ax, offset msg
call put_string
mov ah,1h
int 21h
mov bl,al
cmp bl,'A'
je add_num cmp bl, 'a'
je add_num cmp bl,'S'
je sub_num cmp bl,'s'
je sub_num
jne finishadd_num:
mov ax, offset msg1
call put_string
call get_num
mov num1, ax
mov ax, offset msg2
call put_string
call get_num
mov num2, ax
mov ax, offset num
call put_string
mov ax, num1
add ax, num2
call put_num
jmp finish
sub_num:
mov ax, offset msg1
call put_string
call get_num
mov num1, ax
mov ax, offset msg2
call put_string
call get_num
mov num2, ax
mov ax, offset num
call put_string
mov ax, num1
sub ax, num2
call put_num
jmp finish
finish:
mov ax, 4c00h
int 21h
put_string:
mov dx, ax
mov ah, 9h
int 21h ret
get_char:
mov ah, 1h
int 21h ret
put_char:
mov dl,al
mov ah, 2h
int 21h ret
get_num:
push bx
push cx
push dx
mov dx, 1
mov bx, 0
mov cx, 0
call get_char
cmp al, ' '
jne newline
mov dx, -1
call get_char
newline:
push dx
cmp al, 13
je fin_read
sub al, '0'
mov bl, al
mov ax, 10
mul cx
mov cx, ax
add cx, bx
call get_char
read_loop:
cmp al, 13
je fin_read
sub al, '0'
mov bl, al
mov ax, 10
mul cx
mov cx, ax
add cx, bx
call get_char
jmp read_loop
fin_read:
mov ax, cx
pop dx
cmp dx, 1
je fin_getn
neg ax
fin_getn:
pop dx
pop cx
pop bx
ret
put_num:
push bx
push cx
push dx
mov dx, 0
push dx
mov cx,10
cmp ax, 0
jge calc_digits
neg ax
push ax
mov al, ' '
call put_char
pop ax
calc_digits:
div cx
add dx, '0'
push dx
mov dx, 0
cmp ax, 0
jne calc_digits
display_loop:
pop ax
cmp ax, 0
je end_display_loop
call put_char
jmp display_loop
end_display_loop:
pop dx
pop cx
pop bx
ret
end start

No comments: