I tried to make calculator using assembly language, here is my code:
.model small
.stack 100h
.data
greeting db ‘WELCOME TO YOUR CALCULATOR’, 0Dh, 0Ah, ‘$’
menu db ‘1 – ADDITION’, 0Dh, 0Ah, ‘2 – SUBTRACTION’, 0Dh, 0Ah, ‘3 – MULTIPLICATION’, 0Dh, 0Ah, ‘4 – DIVISION’, 0Dh, 0Ah, ‘$’
choicePrompt db ‘Enter your choice: $’
prompt1 db ‘Enter 1st Number: $’
prompt2 db ‘Enter 2nd Number: $’
resultMsg db ‘The result is: $’
buffer db 6, 0, 5 dup(0) ; Buffer to store input (max 5 digits)
userChoice db 0
num1 dw 0
num2 dw 0
result dw 0
.code
main proc
mov ax, @data
mov ds, ax
; Print the greeting and menu
lea dx, greeting
mov ah, 09h
int 21h
lea dx, menu
mov ah, 09h
int 21h
; Print choice prompt
lea dx, choicePrompt
mov ah, 09h
int 21h
; Read user's choice
mov ah, 01h
int 21h
sub al, '0'
mov userChoice, al
call getch
; Print newline
call printNewline
; Print prompt1 and read first number
lea dx, prompt1
mov ah, 09h
int 21h
call readNumber
mov num1, ax
call printNewline
; Print prompt2 and read second number
lea dx, prompt2
mov ah, 09h
int 21h
call readNumber
mov num2, ax
; Perform the chosen operation
mov ax, num1
mov bx, num2
cmp userChoice, 1
je additionOp
cmp userChoice, 2
je subtractionOp
cmp userChoice, 3
je multiplicationOp
cmp userChoice, 4
je divisionOp
jmp endProgram
additionOp:
add ax, bx
mov result, ax ; Store the result
jmp displayResult
subtractionOp:
sub ax, bx
mov result, ax ; Store the result
jmp displayResult
multiplicationOp:
mul bx
mov result, ax ; Store the result
jmp displayResult
divisionOp:
xor dx, dx
div bx
mov result, ax ; Store the result
jmp displayResult
displayResult:
; Print the result message
lea dx, resultMsg
mov ah, 09h
int 21h
; Print the actual result
mov ax, result
call printNumber
; Print a newline
call printNewline
ret
endProgram:
mov ah, 4Ch
int 21h
main endp
getch proc
mov ah, 07h
int 21h
ret
getch endp
readNumber proc
lea dx, buffer
mov ah, 0Ah
int 21h
lea si, buffer + 2
mov ax, 0
mov cx, 0
convertLoop:
lodsb
cmp al, 0Dh
je endConvert
sub al, ‘0’
mov bx, 10
mul cx
add cx, ax
jmp convertLoop
endConvert:
mov ax, cx
ret
readNumber endp
printNewline proc
mov ah, 02h
mov dl, 0Dh
int 21h
mov dl, 0Ah
int 21h
ret
printNewline endp
printNumber proc
mov bx, 10
xor cx, cx
convertLoop2:
xor dx, dx
div bx
add dl, ‘0’
push dx
inc cx
cmp ax, 0
jne convertLoop2
printLoop:
pop dx
mov ah, 02h
int 21h
loop printLoop
ret
printNumber endp
end main
The menu is ok but when it prints the result it only shows 0 as the results in add, sub, and mul but when I tried the division it shows “divide error – overflow” and it doesn’t show the resut. I’m only a beginner so please help.
Gigi20 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.