


Posted on 06192006, by Tim
Like subtraction, LC3 does not natively support multiplication. We are once again going to have to develop our own algorithm.
Multiplication is really a series of additions. Take for example 5 x 4. It can really be viewed as 5 + 5 + 5 + 5. This is how we have to treat multipication in LC3 programming.
We need to set up a few labels. We will need to know the two numbers we are multiplying. Let's use 4 and 5.
Code:  FIRST_NUMBER .fill #5
SECOND_NUMBER .fill #4 
Now we have to start the heart of our program. We will use a blank register to store the sum of our operations. We want to enter into a loop that will decrement #4 until it reaches #0. This is the best way to keep track of how many times we have added 5 to the sum.
Code:  ; R1 is our sum
AND R1, R1, #0 ; set R1 to zero
LD R2, FIRST_NUMBER
LD R3, SECOND_NUMBER
; enter loop
MULTIPLY ADD R1, R1, R2 ; add to sum
ADD R3, R3, #1 ; decrement our counter
BRp MULTIPLY ; continue until the 2nd num is 0 
We can write more versatile programs than this. Instead of multiplying two static values, let's grab two numbers from the user and multiply them. For simplicity, we will only grab one digit numbers.
Code:  .ORIG x3000
; R1 is our sum
AND R1, R1, #0 ; set R1 to zero
; R3 is our counter
AND R3, R3, #0
; R4 is our inverse ascii offset
LD R4, INVERSE_ASCII_OFFSET
; output prompt
LEA R0, PROMPT
PUTS
; get first character
GETC
OUT
; store character in R5
ADD R5, R0, #0
; get real value of R5
ADD R5, R5, R4
; output prompt
LEA R0, PROMPT
PUTS
; get second character
GETC
OUT
; store character in R2
ADD R2, R0, #0
; get real value of R2
ADD R2, R2, R4
; set R2 as our counter
ADD R3, R2, #0
; enter loop
MULTIPLY:
ADD R1, R1, R5 ; add to sum
ADD R3, R3, #1 ; decrement our counter
BRp MULTIPLY ; continue until the 2nd num is 0
HALT
INVERSE_ASCII_OFFSET .fill #48
PROMPT .stringz "Enter a number: "
.END 
Our product is stored in R1.
Difficulty: Intermediate  Views: 26730
chaoscreater wrote:  how does it enter the "MULTIPLY" loop?? Don't you have to specify it?? E.g.

Adrian wrote:  Chaoscreater  even though code is labeled, it will still be executed if it is the next instruction to execute. You don't need to explicitly say because after Code:  ; set R2 as our counter
ADD R3, R2, #0  executes, it will go to the next line  the multiply routine, and that will execute. Remember, labels dont stop code execution, they just let us jump to specified locations. Its not the same as a function definition in c, which it sounds like you were expecting. 
chaoscreater wrote:  ahh I see. Thanks for clarifying! 

