Microsoft PowerPoint – Array Examples.pptx
Sigma16: Array Examples
from Section 7
Example: Sum an array
Example: Given an array x[0], …, x[n-1], write an assembly
language program, Sum, to compute the sum of the elements.
Test the program with a 5 element array as follows:
{17, 2, 150, -3, 25}
Systems and Networks Sigma16 Examples
Solution
Step 1: High level algorithm. A traversal over an array with a known number of
elements can be done with a for-loop, thus:
; sum = 0;
; for (i = 0; i
; {
; if (x[i] > max)
; { max=x[i]; }
; i++;
; }
Systems and Networks Sigma16 Examples
Solution: Part II
; Usage of the registers:
; R1 = max
; R2 = i
; R3 = -1
; R4 = x[i]
; R5 = 1
Systems and Networks Sigma16 Examples
Initialisation
load R1,x[R0] ; max = x[0]
lea R2,1[R0] ; i = 1
lea R3,-1[R0] ; R3 = -1
lea R5,1[R0] ; R5 = 1 (for counter)
Systems and Networks Sigma16 Examples
Loop
loop load R4,x[R2] ; R4 = x[i]
cmpgt R6,R4,R3 ; R6 = (x[i] > -1)
jumpf R6,done[R0] ; go to done if x[i] <= -1
cmpgt R6,R4,R1 ; R6 = (x[i] > max)
jumpf R6,skip[R0] ; go to skip if x[i] <= max
add R1,R4,R0 ; max = x[i]
skip add R2,R2,R5 ; i++
jump loop[R0] ; go to loop
done store R1,max[R0] ; store result in max
trap R0,R0,R0 ; terminate
Systems and Networks Sigma16 Examples
The data area
; The data area:
x DATA 2 ; x[0]
DATA 42 ; x[1]
DATA 224 ; x[2]
DATA 19 ; x[3]
DATA 4 ; x[4]
DATA -1 ; indicates end of the positive data
max DATA 0 ; declare max and initialise to 0
Systems and Networks Sigma16 Examples