Home > OS >  Keeping a running total of numbers entered LMC
Keeping a running total of numbers entered LMC

Time:10-28

I am making a program that allows a user to input numbers indefinitely until they input '0'. Once they enter 0 the program should halt. However, I want to add each number entered to a running total and output the total everytime the user inputs a new number. For example:

Input = 2
Total = 2
Input = 2
Total = 4
Input = 3
Total = 7
Input = 0
Program stops

Code:

START   INP    
        ADD TOTAL
        OUT
        BRA START
        HLT

TOTAL   DAT 000

The code above takes user input indefinitely but outputs single numbers (Does not keep a running total). I am wondering how I would keep a running total of all numbers entered and also stop the program when the user enters 0 in LMC. Thanks in advance.

CodePudding user response:

There are just two things missing in your code:

  • The test whether the input was zero and stop the program. This you can do with a simple BRZ instruction right after the input was made, and let it branch to the HLT instruction -- which will need a label for that purpose.

  • The update of the total every time you have calculated the sum. Currently you "forget" the sum once you have output it, and so in the next cycle the total will still be zero. Just add a STA TOTAL right after have done the addition.

Here is a runnable snippet:

START   INP
        BRZ STOP   # stop when user entered 0
        ADD TOTAL
        STA TOTAL  # save result, so it accumulates
        OUT
        BRA START
STOP    HLT

TOTAL   DAT 000



<script src="https://cdn.jsdelivr.net/gh/trincot/[email protected]/lmc.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related