What are loops in assembly language?
A loop is a block of statements that are repeatedly executed until a condition is satisfied.
The assembly language uses JMP instruction to implement loops. However, the processor set can use the LOOP instruction to implement loops conveniently.
Syntax and explanation
The following code snippet illustrates how a loop is implemented through JMP instruction:
mov AL, 5 ; store the number of iteration in ALL1:(loop code)DEC AL ; decrement ALJNZ L1
- The number of iterations of the loop is stored in
AL. - At the end of each iteration, the code decrements
AL, then takes a conditional jump ifALis not zero.
The following code snippet illustrates how a loop is implemented through the loop instruction:
mov ECX 5 ; store the number of iterations in ECX registerL1:(loop code)loop l1
- The
loopinstruction always extracts the number of iterations from theECXregister. - The
loopinstruction decrements the value ofECXand compares it with zero. - If the value in
ECXis equal to zero, the program jumps to theL1label; otherwise, the program exits the loop.
Examples
The following code illustrates the use of loop instruction using the X86 instruction set to print the first 10 numbers:
section .textglobal _start ;must be declared for using gcc_start: ;tell linker entry pointmov rcx,10 ;loop runs until the value of rcx is 0mov rax, '1' ;rax holds the character that needs to be printedl1: ;loop startsmov [num], rax ;value in rax moved to variable nummov rax, 4 ;4 is the system call number for the write system callmov rbx, 1 ;1 is the file descriptor for the output streampush rcx ;value of rcx pushed to stack and stored here temporarily;rbx, rcx and rdx are arguments to the write system callmov rcx, num ;num moved to rcx, as rcx contains the character that will be printedmov rdx, 1 ;1 is the size (1 byte) of the character that is to be printedint 0x80 ;interrupt that executes the write system call in kernel modemov rax, [num] ;the first character has been output, value of num moved to eaxsub rax, '0' ;converts character in eax to decimalinc rax ;increments decimal value in eax by 1add rax, '0' ;converts decimal back to characterpop rcx ;pops back value of ecx temporarily stored on the stackloop l1 ;loops, value of ecx auto decrementedmov eax,1 ;system call number (sys_exit)int 0x80 ;call kernelsection .bssnum resb 1
- The
raxregister stores the iteration number, and thercxregister stores the total number of iterations and is initialized to 10. - The
l1block represents the loop code. At each iteration, the iteration count in thercxregister is pushed onto the stack. The current value ofraxis moved torcx, and a write system call is made, which prints the number on the screen. raxis incremented, and the iteration count is popped from the stack into thercxregister. The program then decrementsrcxand jumps tol1using theloopcommand ifrcxis greater than 0.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved