Use of LOOP instruction
Loop instruction is a dedicated instruction which can be used whenever you want to execute some instructions repeatedly. This instruction uses only CX register as counter.
The sequence of operations performed by loop instruction are
· Decrement CX by 1 i.e., CX=CX-1
· Check if CX≠0, Repeat executing instructions from specified label
For example, if you use instruction LOOP L1, it would do following operations.
DEC CX; Subtract '1' from destination operand CX.
· CMP CX, 0; Compare CX with 0;
· JNE L1; If CX is not equal to 0, jump to label L1;
Traversing array using INC, DEC and LOOP instructions.
Following is an example using LOOP instruction instead of conventional CMP and JMP instructions. This program adds adjacent elements from two arrays VEC1 & VEC2 and places their sum in third array VEC3. At the end of program, result in third array VEC3 will be VEC3 DB 04,07,0B,07.
LEA SI, VEC1
LEA BX, VEC2
LEA DI, VEC3
MOV CX, 4
L1:
MOV AL, [SI]
ADD AL, [BX]
MOV [DI], AL
INC SI; ; adds ‘1’ to the destination operand.
INC BX;
INC DI;
LOOP L1; ; Decrements CX each time and keeps executing instructions from label L1 till CX becomes 0.
RET
VEC1 DB 1, 2, 5, 6
VEC2 DB 3, 5, 6, 1
VEC3 DB ?, ?, ?, ?
No comments:
Post a Comment