LMC Sample Program

The triangular numbers are as follows:   

 1     =    1
 3     =    1 + 2
 6     =    1 + 2 + 3
 10    =    1 + 2 + 3 + 4
 15    =    1 + 2 + 3 + 4 + 5
 21    =    1 + 2 + 3 + 4 + 5 + 6
 etc.

The series begins with 1 (the first triangular number).  To calculate the nth triangular number, n is added to the previous triangular number.  For example, the fourth triangular number is calculated by adding 4 to the third triangular number (which is 6), i.e. 10 = (1 + 2 + 3) + 4.

Write a program that takes a single value (greater or equal to zero) as input and outputs which triangular number it is or 0 if it is not a trinangular number.  For example, if the input is 15, the output will be 5 (15 is the 5th triangular number); and if the input is 7, the output will be 0 (7 is not a triangular number).

Flowchart

The flowchart for the above program is shown below.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Program

INP
STA VALUE
LDA ZERO
STA TRINUM
STA N
LOOP LDA TRINUM
SUB VALUE
BRP ENDLOOP
LDA N
ADD ONE
STA N
ADD TRINUM
STA TRINUM
BRA LOOP
ENDLOOP LDA VALUE
SUB TRINUM
BRZ EQUAL
LDA ZERO
OUT
BRA DONE
EQUAL LDA N
OUT
DONE HLT
VALUE DAT 000
TRINUM DAT 000
N DAT 000
ZERO DAT 000
ONE DAT 001

What you should do

  1. Click on the "LMC Simulator Applet" link to start the LMC simulator.
  2. Clear the Message Box and all of the LMC mailboxes -- click the "Clear Messages" button and the "Clear" button if necessary.
  3. Copy the twenty eight line program above and paste it into the Message Box
  4. Click on the "Compile Program" button.
  5. Click on the "Run" button.
  6. When prompted, enter three-digit numbers in the "In-Box", and press the "Enter" button.

What you should see