Home > Software engineering >  Change a program to output two numbers in Ascending order instead of descending
Change a program to output two numbers in Ascending order instead of descending

Time:10-11

This is descending. How would I swap to ascending so that when LMC outputs the numbers it shows in ascending order.

        INP
        STA A 
        INP
        STA B
        LDA A
        SUB B
        BRP BTOS
        BRA BTOS2
BTOS    LDA A
        OUT
        LDA B
        OUT
BTOS2   LDA B
        OUT
        LDA A
        OUT
A       DAT
B       DAT

CodePudding user response:

You just have the logic backwards. You are checking if A - B is positive (i.e. A is larger) and if it is you are outputting A then B, which is descending. You also need to halt the program after the BTOS branch ends, otherwise you will jump to the second condition after the first completes in the case that B is greater than A

        INP
        STA A 
        INP
        STA B
        LDA A
        SUB B
        BRP BTOS
        BRA BTOS2
BTOS    LDA B
        OUT
        LDA A
        OUT
        HLT
BTOS2   LDA A
        OUT
        LDA B
        OUT
        HLT
A       DAT
B       DAT

You also need to halt the program after the BTOS branch ends, otherwise you will jump to the second condition after the first completes in the case that B is greater than A.

CodePudding user response:

As already indicated BRP BTOS will branch when the subtraction of B from A is positive, in other words, when A is not less than B. So in that case you should first output B. And once the output is done, the program should stop: this halt is missing in the first block.

It is also a pity that:

  • You do not use the accumulator's value that is there after the second input, as it already holds the value of B and you can immediately continue to subtract A from that.

  • There are two branch instructions when it could be done with just one.

  • The labels have cryptic names -- I have no idea what BTOS stands for here.

Here is how I would suggest to do it:

#input: 35 12
        INP
        STA A 
        INP
        STA B
        SUB A
        BRP first_a
        LDA B
        OUT
        LDA A
        OUT
        HLT
first_a LDA A
        OUT
        LDA B
        OUT
        HLT
A       DAT
B       DAT

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

  • Related