I am trying to write a program in Easy68K to calculate the sum of the elements of an array, but it freezes at ().
Maybe I didn't fully understand how a0
, (a0)
, and the sum work. Could someone help me?
Here is my code:
ORG $8000
array DC 1,2,3,4,5,6,7,8,9,10 ; DC reserves 4 bytes for each element
; $8000 -> 1, $8004 -> 2, etc.
len EQU 10 ; Number of elements in the array
sum DC 0 ; Variable to store the sum
START:
suba.l a0,a0 ; Clear register A0 (set to 0)
clr d1
clr d0
movea array,a0 ; Load the address of 'array' into A0
move len,d1
move sum,d0
LOOP:
TST d1 ; Check if D1 (counter) is zero
beq END ; If zero, exit the loop
move (a0),d5 ; Load the value at address A0 into D5
add d5,d0 ; Add D5 to D0 (accumulate sum)
addq #4,a0 ; Move to the next element in the array (4-byte step)
subq #1,d1 ; Decrease the loop counter by 1
bra LOOP
END:
SIMHALT
END START
array DC 1,2,3,4,5,6,7,8,9,10 ; DC reserves 4 bytes for each element
Don't omit the size specifier from your directives and instructions! From the screenshot it is clear that a naked DC
reserves just a 2-byte word and not the 4 bytes that you claim and use thoughout your program.
suba.l a0,a0 ; Clear register A0 (set to 0) clr d1 clr d0
No need for clearing these if you're going to assign them in full.
move (a0),d5 ; Load the value at address A0 into D5 add d5,d0 ; Add D5 to D0 (accumulate sum) addq #4,a0 ; Move to the next element in the array (4-byte step)
There's no need for a separate increment of the address register. 68k has the "post-increment" addressing mode that does that automatically:
move.l (a0)+, d5 ; Load the value at address A0 into D5
add.l d5,d0 ; Add D5 to D0 (accumulate sum)
This code should work:
ORG $8000
array DC.l 1,2,3,4,5,6,7,8,9,10 ; DC.l reserves 4 bytes for each element
len EQU 10 ; Number of elements in the array
sum DC.l 0 ; Variable to store the sum
START:
movea.l array, a0 ; Load the address of 'array' into A0
move.b len, d1
clr.l d0
LOOP:
add.l (a0)+, d0 ; Add longword at A0 to D0, and post-increment A0 by 4
subq.b #1, d1 ; Decrease the loop counter by 1
bne.s LOOP
move.l d0, sum ; Copy to memory-based variable (should it be needed)
SIMHALT
END START
add.l (a0)+, d0
will add the longword at the address A0 to D0 and then raise the contents of A0 by the size of the operation (longword means 4).bra
in the end. Always try to 'conditionally' jump to the top of the loop.