Search code examples
assemblydosx86-16

Calculate square of number and store them in dw in assembly 8086 masm


I am trying to calculate the square of 5 using brute force, so I tried this but it does not store anything in dwand I define dw like this result dw 2 dup(?)

mov ax, 5
mov bx, 5
mov cx, 1
mov dx, ax
loop1:
 add ax, dx

 cmp bx, cx
 je endLoop

 add cx, 1
 jmp loop1

endLoop:
 mov result, ax

Solution

  • calculate the square of 5

    5^2 = 25 but your code produces 30

    Your loop does 5 additions in total (1x in the fallthrough and 4x in the jump back).
    Since AX starts out with its original value, you get too much!

    Either start AX at zero or do 1 iteration less:

     mov ax, 5
     mov bx, 5
     mov cx, 1
     mov dx, ax
     XOR AX, AX   ; start at zero
    loop1:
     add ax, dx
    
     cmp bx, cx
     je endLoop
    
     add cx, 1
     jmp loop1
    

    -

     mov ax, 5
     mov bx, 5
     mov cx, 1+1  ; one iteration less
     mov dx, ax
    loop1:
     add ax, dx
    
     cmp bx, cx
     je endLoop
    
     add cx, 1
     jmp loop1
    

    it does not store anything in dw and I define dw like this result dw 2 dup(?)

    Make sure to setup DS with code like this:

    mov ax, data    ; maybe you'll need 'mov ax, @data'
    mov ds, ax
    

    Try an alternative memory addressing using square brackets:

    mov [result], ax
    

    From comment:

    i am trying to retrieve the result like this
    lea si, result
    inc si
    mov dl, [si]
    mov ah, 2h
    int 21h

    Why do you fetch the second byte of the result? That will probably be plain zero.
    Moreover the result has 2 digits, therefore you need to ouput 2 characters.

    This is a solution from one of my other recent answers:

    mov ax, [result]     ; AX=25
    mov bl, 10
    div bl               ; AL=2   AH=5
    add ax, "00"         ; AL='2' AH='5'
    mov dx, ax
    mov ah, 02h
    int 21h              ; Outputs the character in DL='2'
    mov dl, dh
    mov ah, 02h
    int 21h              ; Outputs the character in DL='5'