DYSTOPIANPIXEL

Counted loops

Repeat work with DJNZ and understand the zero-counter case.

Next Asset Lab concept artwork showing sprite patterns, palette colours and animation frames
Next Asset Lab concept artwork · Begin with Odin Dev.2k and the foundations of Z80 assembly.
TUTORIAL 2 / PART 08

Loops: repeating an instruction without copying it

A loop is a section of code that runs several times. We could write INC A three times, but real programmes often need to repeat an operation many times. The Z80 instruction DJNZ is a convenient first example: Decrement B and Jump if Not Zero.

start:
    ld b,$03
    ld a,$00
again:
    inc a
    djnz again
    ld hl,$6000
    ret

LD B,$03 prepares a three-iteration counter. LD A,$00 starts the result at zero. Each time the CPU visits again, INC A increases A by one. DJNZ again decreases B by one and jumps backwards if B is not zero.

First$01$02Yes
Second$02$01Yes
Third$03$00No

Expected after R: A = $03, B = $00, HL = $6000. DJNZ does not modify the flag register. INC A does update several flags, but not Carry; this distinction matters whenever code checks a previous flag.

Why starting B at zero is dangerous here

DJNZ always decrements B before testing it. If B starts at $00, the first decrement wraps to $FF rather than leaving zero. The loop then continues until the counter eventually wraps back to zero, giving 256 iterations, not zero. This example is finite, but a more complex body could make an incorrect counter a serious problem. For an optional zero-length job, check the count before entering a DJNZ loop.

Do not confuse a loop counter with a stack counter

B is a general CPU register; in this example we chose it as a counter. The Stack Pointer (SP) is unrelated. When the loop ends, B is zero. If a calling routine needed the old B value, our loop has changed it — a problem we will address when defining subroutine responsibilities.