Your place is saved automatically on this browser.
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.
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.
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.
