Search code examples
assemblyimperative-programmingz80

z80 Assembly nested loops


I need to write three nested loops in Assembly on a z80 hardware. The first loop (the most internal one) should iterate 70 times, the other two 100 times.

This is the code I have come up with, but it seems not to work properly; it iterates until an interrupt is generated (Stack-Overflow error, I think).

loop1:
ld a, 46h
   loop2:
   ld b, 64h
      loop3:
      ld c, 64h
      dec c
      jnz c, (loop3)
   dec b
   jnz b, (loop2)
dec a
jnz a, (loop1)
halt

A similar code in C++ would be

for(int b = 100; c>0; c--)
   for(int c = 100; b>0; b--)
      for(int a = 70; a>0; a--)
       ...

Solution

  • This is how you initialize loops:

    ld a, 46
    loop1:
       ld b, 64
       loop2:
          ld c, 64
          loop3:
          dec c
          jnz c, loop3
       dec b
       jnz b, loop2
    dec a
    jnz a, loop1
    halt