LMC Branch Instructions (for implementing
loops)
The following program will demonstrate how to use the
branching instructions of the LMC to implement looping. Note: The Branch
Always instruction should only be used to connect paths indicated by your
flowchart.
Flowchart
The following is the flowchart
for a program that will output the values from 1 to 10.
Program
LDA ONE
STA COUNT
OUT
LOOPTOP LDA COUNT
ADD ONE
OUT
STA COUNT
SUB TEN
BRP ENDLOOP
BRA LOOPTOP
ENDLOOP HLT
ONE DAT 001
TEN DAT 010
COUNT DAT
What you should do
- Click on the "LMC
Simulator Applet" link to start the LMC simulator.
- Clear the Message Box and
all of the LMC mailboxes -- click the "Clear Messages" button
and the "Clear" button if necessary.
- Copy the fourteen line
program above and paste it into the Message Box
- Click on the "Compile
Program" button.
- Click on the
"Run" button.
- When prompted, enter
three-digit numbers in the "In-Box", and press the
"Enter" button.
What you should see
- After the program is
compiled, you should see from mailbox 0 to 9 the instructions 511, 313,
902, 513, 111, 902, 313, 212, 810, 603. The Program Counter should
start at 0 (click on "Reset" if necessary).
- DAT reserves mailbox 11 for
ONE, mailbox 12 for TEN, and mailbox 13 for COUNT. A three-digit
number after DAT represents the initial value that the compiler should
store in the mailbox (e.g. 001 for ONE and 010 for TEN).
- The LOOPTOP identifier is
the first instruction in the loop. When the code in the loop has
been executed, a BRANCH always instruction (e.g. BRA LOOPTOP) causes the
LMC to "jump" back to the start of the loop so that the code
section can be executed again.
- When you click on
"Run" or "Step", the Message Box will describe the
actions of each instruction.
- The first three
instructions initialize the COUNT mailbox to 1 and output this value to
the Out-Box.
- In the body of the loop,
COUNT is loaded onto the Accumlator, one is added to it, the new value is
output, and then the new value of COUNT is stored back to its
mailbox. The value of COUNT must be repeatedly loaded and stored
because the value of COUNT is erased from the Accumulator when the loop
termination condition is checked.
- The SUB instruction is used
as part of checking the loop termination condition. The loop is to
execute ten times. The SUB TEN instruction subtracts ten from the
value of the Accumulator.
- If the value of the
Accumulator is smaller, subtracting TEN from it will cause the
Accumulator to become negative. The BRP instruction will then do
nothing, and the program will continue to mailbox 9. Mailbox 9 represent the completion of the loop, so its
instruction (BRA LOOPTOP) causes the LMC to return to the top of the loop
so that it can be executed again.
- When the value of the
Accumulator/COUNT becomes ten, subtracting TEN from it will cause the
Accumulator to become zero. The BRP instruction will now update the
Program Counter to ENDLOOP (mailbox 10).