loopsassemblyx86

How do I implement this until statement in assembly language?


b) sum = 0; count = 1; repeat (add count to sum; add 1 to count); until (sum > 5000) or (count = 40);
Answer:
    mov sum, 0
    mov ecx, 1
untilB: add sum, ecx
    inc ecx
    cmp sum, 5000
    **what comes after this?**
enduntilB:

So what kind of jump statements should I use for each condition (sum > 5000 or count = 40)?

Also:

c) sum = 1000; for count = 100 downto 50 (subtract (2 * count) from sum); end for;
Answer:
    mov sum, 1000
    mov ecx, 100
forC:   cmp ecx, 50
    jnge endforC
    **what comes after this?**
    dec ecx
    jmp forC
endforC:

Solution

  • Something like this:

        mov sum, 0
        mov ecx, 1
    untilB: add sum, ecx
        inc ecx
        cmp sum, 5000
        jg enduntilB
        cmp ecx, 40
        je enduntilB
        jmp untilB
    enduntilB:
    
        mov sum, 1000
        mov ecx, 100
    forC:   cmp ecx, 50
        jl endforC
        imul eax, ecx, 2
        //
        // alternatively:
        // mov eax, ecx
        // shl eax, 1
        //
        // alternatively:
        // mov eax, ecx
        // add eax, eax
        //
        sub sum, eax
        dec ecx
        jmp forC
    endforC: