s

8086 LOOP Instruction edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 13 February 2021 | 4889

Loop instruction is a Transfer Of Control Instruction in 8086 assembly language. Loop instructin transfers the control to a specific label or jumps to specific label If CX is not equal to zero after auto decrement. Its used for looping though a set of instructions and you can specify the number of times the loop have to execute in the CX register. This instruction does not affect any flag.

Algorithm

Decrease CX, jump to label if CX not zero.

CX = CX - 1
if CX <> 0 then
	jump
else
	no jump, continue

Sample Code

In the below code we will try to print hello world 10 times

.model tiny
.code
org 100h


main proc near

mov cx,10d
loop1:
    push cx	; Best practice, I am pushing the value of cx to the stack and poping it out just 
		; before the loop instruction, This is done to avoid cx from being modified by 
		; the set of instructions below between the label loop1 and loop instruction
    mov ah,09h  ; dos function to print a string
    mov dx,offset message   ; memory location of message to print
    int 21h     ; dos interrupt 21h
    pop cx
loop loop1	; here the value of cx is decremented by 1 and if the value of cx is not zero after decrement then control is transfered to loop1

mov ah,4ch	; dos funcion to terminate and return to dos
mov al,00
int 21h  	; dos interrupt 21h  

ret
endp
message db 'hello world',0ah,0dh,'$'    ; string ends with $, 0ah is carriage return, 0dh is line feed
end main