1

I know that I need to do repeated addition, but I'm having trouble with the loops; I just do not understand them at all.

Here is a program that multiplies a number by 2, without a loop.

INP
STA num1
LDA num1
ADD num1
STA num1
OUT
HLT
num1 DAT

I know that I need to add a loop, but I'm just lost. Where do I put the loop? How do I construct a loop with the LMC's branch commands?

The end result of my project is a program that will multiply two numbers together, depending on what the user inputs. For example, if 4 and 5 were input, the program would carry out the equation 4 + 4 + 4 + 4 + 4 = 20. I do not know how to construct a loop to carry this out, and I've been staring blankly at the instructions set for days.

ciarascuro
  • 21
  • 2
  • 6

2 Answers2

1

In words:

 Read input into R0 and R1.
 Set RESULT to 0
 While R1 > 0 {
     Subtract 1 from R1
     Add R0 to RESULT
 }
 Output RESULT

In LMC assembler:

     INP
     STA R0
     INP
     STA R1

LOOP LDA R1
     BRZ END
     SUB ONE
     STA R1
     LDA RES
     ADD R0
     STA RES
     BRA LOOP

END  LDA RES
     OUT

     // Temporary storage
R1   DAT
R0   DAT
RES  DAT

     // Constants
ONE  DAT 1

You can see it running here: multiplication on LMC emulator

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
0

I have made a program like this before, it should go as follows with the same ram addresses if memory serves. This flowchart should also help explain this. http://creately.com/diagram/example/i5z9v65u1/Multiplication%20LMC

INP
STA X
INP
STA Y
LOOP LDA Y
BRZ END
LDA ANSWER
ADD X
STA ANSWER
LDA Y
SUB ONE
STA Y
BRA LOOP
END LDA ANSWER
OUT
HLT
ONE DAT 1
ANSWER DAT 0
X DAT 0
Y DAT 0
The Boat
  • 27
  • 7