Assembly Language Flow Control FOR ... NEXT in Z80 Assembly


Example

The Z80 has a specific instruction to implement loop counts: DJNZstanding for "decrement B register and jump if not zero". So, B is the register of choice to implement loops on this processor. FOR...NEXT needs to be implemented "backwards", because the register counts down to zero. Other CPUs (like the 8086, this CPU uses the CX register as loop counter) might have similar specific loop counter registers and instructions, some other CPUs allow loop commands with arbitrary registers (m68k has a DBRA instruction that works with any data register).

; Trivial multiplication (by repeated adding, ignores zero in factors, so 
; not recommended for general use)
;
; inputs:    A = Factor 1
;            B = Factor 2
;
; output:    A = Factor 1 * Factor 2
;
; Pseudo code
; C = A : A = 0 : FOR B = Factor 2 DOWNTO 0 : A = A + C : NEXT B

mul:
     LD    C,A        ; Save Factor 1 in C register
     XOR   A          ; Clear accumulator
mLoop:
     ADD   A,C        ; Add Factor 1 to accumulator
     DJNZ  mLoop      ; Do this Factor 2 times
     RET              ; return to caller