0

100x100 array A of integers, one byte each, is located at A. Write a program segment to compute the sum of the minor diagonal, i.e.

SUM = ΣA[i,99-i], where i=0...99

This is what I have so far:

LEA A, A0
CLR.B D0
CLR.B D1
ADDA.L #99, D0
ADD.B (A0), D1
ADD.B #1, D0
BEQ Done
ADDA.L #99,A0
BRA loop
5
  • 1
    Welcome to StackOverflow! It doesn't seem like you're actually asking a question anywhere here. What specifically are you asking? Mar 18, 2013 at 3:15
  • I'm currently unable to test the code out so I was wondering if the code that I have written looks correct. Mar 18, 2013 at 3:27
  • You mean 99-i (ninety nine minus eye), not 99-1 (ninety nine minus one), right? What CPU is this for? Mar 18, 2013 at 3:32
  • Correct...sorry about that. Mar 18, 2013 at 3:33
  • 1
    You're incrementing D0, when it should probably be decremented. I'd consider removing the branch to Done and using a dbra construct for the loop.
    – JasonD
    Mar 18, 2013 at 8:19

1 Answer 1

1

There's quite many issues in this code, including (but not limited to):

  • You use 'Loop' and 'Done', but the labels are not shown in the code
  • You are adding 100 bytes in D1, also as a byte, so you are definitely going to overflow on the results (the target of the sum should at least be 16 bit, so .w or .l addressing)
  • I'm perhaps wrong but I think the 'minor diagonal' goes from the bottom left to the upper right, while your code goes from the top left to the bottom right of the array

On the performance side:

  • You should use the 'quick' variant of the 68000 instruction set
  • Decrement and branch as mentioned by JasonD is more efficient than add/beq

Considering the code was close enough from the solution, here is a variant (I did not test, hope it works)

    lea A+99*100,a0     ; Points to the first column of the last row
    moveq #0,d0         ; Start with Sum=0
    moveq #100-1,d1     ; 100 iterations
Loop    
    moveq #0,d2         ; Clear register long
    move.b (a0),d2      ; Read the byte
    add.l d2,d0         ; Long add
    lea -99(a0),a0      ; Move one row up and one column right
    dbra d1,Loop        ; Decrement d1 and branch to Loop until d1 gets negative
Done
    ; d0 now contains the sum

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.