I\'m trying to find sum from 1 to 10 in assembly. Should equal 55 . But I kept g
ID: 3801376 • Letter: I
Question
I'm trying to find sum from 1 to 10 in assembly. Should equal 55. But I kept getting g6. Can someone fix my .asm code. Thanks.
---------------------------------------------------------------
section .text
global _start ;must be declared for linker (ld)
_start:
mov eax,10 ;number bytes to be summed
mov ebx,0 ;EBX will store the sum
mov ecx, x ;ECX will point to the current element to be summed
top: add ebx, [ecx]
add ecx,1 ;move pointer to next element
dec eax ;decrement counter
jnz top ;if counter not 0, then loop again
done:
add ebx, '0'
mov [sum], ebx ;done, store result in "sum"
display:
mov edx,1 ;message length
mov ecx, sum ;message to write
mov ebx, 1 ;file descriptor (stdout)
mov eax, 4 ;system call number (sys_write)
int 0x80 ;call kernel
mov eax, 1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
global x
x:
db 1
db 2
db 3
db 4
db 5
db 6
db 7
db 8
db 9
db 10
sum:
db 0
Explanation / Answer
.model small .stack 100h .data prompt db 13, 10, 'First number:','$' prompt db 13,10, 'Second number:', '$' result db 13, 10, 'Sum','$' ;Variables num1 db ? num2 db ? sum db ? .code main proc mov ax,@data ;get data segment address mov ds,ax ;initialize ds ;Display Prompt mov ah,9 ;print string function mov dx,offset prompt;ds:dx points to string int 21h ; Numbers from the user mov ah,1 ;input function int 21h mov bl,al ;save the value from input mov num1,al mov ah,9 lea dx, prompt ;print prompt int 21h mov ah,2 ;input second function int 21h mov bh,al ;save the value from second input mov num2,al ;Addition mov ax,num1 ;move num1 into ax add ax,num2 ;add first and second numbers together mov sum,ax ;move the total sum of numbers in sum ;Print Sum mov ah,9 lea dx, result ; print result int 21h mov ah,2 mov dl,bl int 21h mov dl,'+' ;display + sign int 21h mov dl,bh int 21h mov dl,'=' ;display = sign int 21h mov dl,bh int 21h mov ah,4ch int 21h main endp end main