Methods of addressing elements of an array were discussed in the chapter 8 in the context of STS and LDS. The next CSC-1 program gives a complete example of a program that has an integer array, and which accesses the elements of this array. The program merely sums up all the elements of the array, stopping at the first negative element. 0: LOOP: LDI 1000 ; Get Array[I] (base address) 1: ADD I ; Add I to base address 2: A2S ; Copy this address to S reg 3: LDS ; Load accum. from this address 4: JN ENDLOOP ; If negative, then done 5: ADD SUM ; Else add to sum 6: STD SUM 7: LOD I ; I := I + 1 8: ADD ONE 9: STD I 10: JMP LOOP ; Go back to top of loop 11: ENDLOOP: HLT ; Halt when done with loop 12: 13: SUM: NUM 0 ; The sum of the array elements 14: I: NUM 0 ; The counter used as array index 15: ONE: NUM 1 ; Constant value 1 16: 16: =1000 ; This tells the assembler to put these ; next values into memory starting at loc. 1000 1000: ARRAY: NUM 47 ; The actual array of values 1001: NUM 82 1002: NUM 3 1003: NUM 26 1004: NUM -1 ; A sentinel value, end of array The style of loops and ifs in this program is not as clear as in the gcd program, so it is not the best program to emulate. The important part to focus on is the accessing of ARRAY[I], which takes place in lines 1 through 4. These lines calculate the address of ARRAY[I] and fetch the integer value at that address, leaving it in the accumulator. |