0

I've been having some trouble with a Z80 assembler code and maybe you could help me out. The code is as follows:

aseg 
org 3000h 
start:   ld A, (tops) 
         ld B, A 
cycle:   add A, B 
         djnz cycle 
rst 38h 
tops: db 3 
end start

The code is supposed to add up the first n integer numbers and the number n would be taken from the memory zone of tops. Thanks for the help

2 Answers2

2

Take into account that if the byte at tops is 0, the loop will actually run 256 times, and the result will overflow. In fact, the result will overflow with any value equal or greater than 23.

This program takes into consideration both issues. Result is in 16 bit HL register.

          ld a,(tops)
          ld hl,0
          ld d,0
          or a
          jr z,EndSum
          ld e,a
Loop:     add hl,de
          dec e
          jr nz,Loop
EndSum:
mcleod_ideafix
  • 11,128
  • 2
  • 24
  • 32
1

When you enter the cycle loop, both A and B contains 3. So you end up with the result 3+3+2+1, which is 9.

If you add an LD A,0 right before you enter the loop you should get 3+2+1 (6), which I assume is the expected result.

Michael
  • 57,169
  • 9
  • 80
  • 125
  • Or, per ye olde standard z80 comments pile: use `xor a` to zero a. It's a byte shorter and as a result slightly faster, both of which can matter with a z80 system. But it's also slightly obtuse, so there's an argument against it. And it's beside the point for the question as set. – Tommy Nov 14 '13 at 03:37