bluegreenocean
bluegreenocean

Reputation: 11

How to find the greatest of more than two input numbers

I was able to write an LMC program which finds the greater value of two input values. But how do I modify it to find the greatest value of any number of input values, not only two?

Below is my code:

START    INP 
         STA NUM1
         INP
         STA NUM2
         LDA NUM1
         SUB NUM2
         BRP Positive
         LDA NUM2
         OUT
         HLT
Positive LDA NUM1
         HLT
NUM1     DAT
NUM2     DAT

Upvotes: 0

Views: 1718

Answers (1)

trincot
trincot

Reputation: 350335

Let NUM1 be the maximum so far, and make a loop to read the next input into NUM2. If the comparison shows that next input is greater, then update NUM1, else not.

With this method it is probably better to rename NUM1 to MAX, NUM2 to just NUM.

You should also determine what will be the indication that all input has been provided. One way to do that is to agree that the user must input a specific value to mark the end of the input. Obviously that means that that special value cannot be part of the input itself.

Here is how it would look if that terminating value is 0:

#input: 5 2 8 4 5 0
START  INP 
       BRZ OUTPUT
       STA MAX
       
LOOP   INP
       BRZ OUTPUT
       STA NUM
       LDA MAX
       SUB NUM
       BRP LOOP ; input was not greater
       LDA NUM
       STA MAX  ; input was greater
       BRA LOOP

OUTPUT LDA MAX
       OUT
       HLT

NUM    DAT 
MAX    DAT 0

<script src="https://cdn.jsdelivr.net/gh/trincot/[email protected]/lmc.js"></script>

Upvotes: 1

Related Questions