Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a loop in x86 assembly language?

I have written the code so far as:

.code

main
 Clrscr

  mov dh,10            ;row 10

  mov dl,20            ;column 20

  call Gotoxy          ;locate cursor

  PromptForIntegers  

    WriteString       ;display string
    ReadInt           ;input integer
  ArraySum

    WriteString       ;display string
    WriteInt          ;display integer

DisplaySum  ENDP

END main

How do I get it to repeat the same steps three times using a loop, clearing the screen after each loop iteration?

like image 576
user267288 Avatar asked Feb 05 '10 18:02

user267288


2 Answers

mov cx,3

loopstart:
   do stuff
   dec cx          ;Note:  decrementing cx and jumping on result is
   jnz loopstart   ;much faster on Intel (and possibly AMD as I haven't
                   ;tested in maybe 12 years) rather than using loop loopstart
like image 55
Arthur Kalliokoski Avatar answered Oct 04 '22 21:10

Arthur Kalliokoski


Yet another method is using the LOOP instruction:

mov  cx, 3

myloop:
    ; Your loop content

    loop myloop

The loop instruction automatically decrements cx, and only jumps if cx != 0. There are also LOOPE, and LOOPNE variants, if you want to do some additional check for your loop to break out early.

If you want to modify cx during your loop, make sure to push it onto the stack before the loop content, and pop it off after:

mov  cx, 3

myloop:
    push cx
    ; Your loop content
    pop  cx

    loop myloop
like image 23
Jeff B Avatar answered Oct 04 '22 21:10

Jeff B