#### Lecture 8 - Oct. 4, 2004

More examples of branching

Example:  multiplication by repeated addition (Patt and Patel  section 6.2.2)

in 'Java'
int a, b, product;
a = 5;  b = 10;
product = 0;
for (int i=a; i>0; i--)
product += b;

in LC-3, with a in R1, b in R2, and product in R3 (and assuming we are allowed to destroy the value in R1)
AND     R3, R3, 0      ; product = 0
ADD     R3, R3, R2     ; product += b
ADD     R1, R1, -1     ; a--
BRP     -3             ; loop if a > 0

we add an infinite loop at the end to 'stop' the machine:
BRNZP   -1             ; infinite loop

and then converting to binary:

0011000000000000      ; start at x3000
0101 011 011 1 00000  ; AND  R3,R3,0
0001 011 011 000 010  ; ADD  R3, R3, R2
0001 001 001 1 11111  ; ADD  R1, R1, -1
0000 001 111111101    ; BRp  -3
0000 111 111111111    ; BRnzp -1

Example:  add up an array of integers
(Patt and Patel p. 134, 167)

in 'Java'
int[] ray = new int[5];
int sum = 0;
for (int i=4; i>=0; i--) sum+= ray[i];

in LC-3
;         array 'ray' starts at x3010
;         R1 : address of ray
;         R2 : i
;         R3 : sum
;
LEA     R1, xF         ; initialize R1 to address of ray
AND     R2, R2, 0
ADD     R2, R2, 4      ; i = 4
AND     R3, R3, 0      ; sum = 0