I am working on the assembly language that adds two user input numbers and then returns the sum. However, my code does not work properly. Can anyone check the issue?
.model small
.stack 100h
.data
message1 db 'Enter the first number: $'
message2 db 'Enter the second number: $'
result_message db 'The sum is: $'
newline db 13, 10, '$'
buffer db 6, ?, 6 dup('$')
num1 dw ?
num2 dw ?
sum dw ?
.code
main:
mov ax, @data
mov ds, ax
; Display message to enter the first number
mov ah, 9
lea dx, message1
int 21h
; Read the first number
mov ah, 0ah ;
lea dx, buffer
int 21h
mov si, offset buffer + 2
mov cx, 0
mov cl, buffer[1]
call convert_to_number
; Store the first number
mov num1, ax
; Display message to enter the second number
mov ah, 9
lea dx, message2
int 21h
; Read the second number
mov ah, 0ah ;
lea dx, buffer
int 21h
mov si, offset buffer + 2
mov cx, 0
mov cl, buffer[1]
call convert_to_number
; Store the second number
mov num2, ax
; Add the numbers
mov ax, num1
add ax, num2
mov sum, ax
; Display the result
mov ah, 9
lea dx, result_message
int 21h
; Convert sum to ASCII
mov ax, sum
call convert_to_ascii ; Fixed error: Corrected procedure call
; Display sum
mov ah, 9
lea dx, buffer + 5 ; Fixed error: Adjusted offset
int 21h
; New line
mov ah, 9
lea dx, newline
int 21h
; Exit program
mov ax, 4c00h
int 21h
convert_to_number:
xor ax, ax
convert_loop:
mov bl, byte ptr [si]
cmp bl, 0
je convert_done
sub bl, '0'
mov dx, ax
mov ax, 10
mul dx
add ax, bx
inc si
jmp convert_loop
convert_done:
ret
convert_to_ascii:
mov bx, 10
mov si, offset buffer + 5
mov byte ptr [si], '$'
convert_loop2:
xor dx, dx
div bx
add dl, '0'
dec si
mov [si], dl
test ax, ax
jnz convert_loop2
ret
end main
I have tried some number changes, but didn't work
Your convert_to_ascii code is correct, but it will never display anything because you have set the DX register to the end of the buffer (where the string terminator $ was placed). Upon returning from convert_to_ascii the SI register is pointing at the first digit of the converted number, so what you need to do is write
mov dx, si.Your convert_to_number has multiple issues!
cmp bl, 0you need to writecmp bl, 13.mov dx, axmov ax, 10mul dxtomov dx, 10mul dx.Since the algorithm does not use CX, better not waste code on retrieving CX from the DOS buffer ...