Search code examples
loopsassemblyx86-16emu8086

SUM numbers 1,2,3,4,5,6,7,8,9,10 by using loop in assembly


I NEED TO SUM numbers 1,2,3,4,5,6,7,8,9,10 by using loop in 8086 assembly. Here my attempt:

    MOV AX,01h
    MOV CX,0ah
LABEL1:
    inc AX
    LOOP LABEL1
    HLT  

Solution

  • You will need a container of some kind to store your sum into. You can choose the register DX for that.

    First make sure to empty this register before starting the loop.
    Then on each iteration of the loop you add the current value of AX to this register DX.

        mov     ax, 1
        mov     cx, 10
        xor     dx, dx    ;This puts zero in DX
    Label1:
        add     dx, ax    ;This adds int turn 1, 2, 3, ... ,10 to DX
        inc     ax
        loop    Label1
    

    Not sure if you're required to use the loop instruction, but an alternative loop uses AX for its loop control.

        mov     ax, 1
        cwd               ;This puts zero in DX because AX holds a positive number
    Label1:
        add     dx, ax    ;This adds in turn 1, 2, 3, ... ,10 to DX
        inc     ax
        cmp     ax, 10
        jbe     Label1
    

    A somewhat better loop adds the numbers from high to low. This way the cmp instruction is no longer needed.

        mov     ax, 10
        cwd               ;This puts zero in DX because AX holds a positive number
    Label1:
        add     dx, ax    ;This adds in turn 10, 9, 8, ... ,1 to DX
        dec     ax
        jnz     Label1