Posted on 10-17-2006, by Tim
In this tutorial, it is assumed that you have read and understand the introduction to branches tutorial.
Loops are pivotal to programming. Since LC-3 has a limited number of instructions, many basic logical and mathematical features are left out from the ISA, therefore you must hand-write a lot of code to perform simple tasks. The most basic function that you can do with loops is multiplication. (For more information on multiplication, see the multiplication tutorial.
All loops have one thing in common: they must eventually terminate. In order to ensure termination, we have a counter variable set up.
|COUNTER .FILL x0005 |
The hex value x0005 will ensure that the loop will run 5 times. We want the loop to terminate once the counter reaches 0.
Next we need a value to multiple. For this example I will use 4.
And finally we'll need a place to store the sum. We'll place that and the counter and the value all in registers (it'll be the first step of the code):
|LD R1, COUNTER
LD R2, VALUE
AND R3, R3, #0 ; let's zero out the total
Can you sense what's going to happen? 4 x 5 is also 4 + 4 + 4 + 4 + 4.
Now we need to begin to set up the loop:
|LOOP ADD R3, R3, R2 ; this adds 4 to an ongoing sum
ADD R1, R1, #-1 ; this decrements the counter by 1
BRp LOOP ; this will jump back to the LOOP label above until R1 is nonpositive
At each iteration of the loop, R3 increases by 4, and R1 decreases by 1. At the end of the program, R3 will hold the value of 20, R1 will hold the value of 0, and R2 will always hold the value of 4.
- Views: 17865