Search code examples
algorithmlogiclittle-man-computer

Summing up values if number of values is given as first input


How do I write a Little Man program that adds up a series of input numbers and outputs the sum. The first input value will contain the number of values that follow as input, and which are to be added together.

I know this can be done by using for loop or while loop.

Here my problem is to count the number of steps. The user may not give any specific number which we can use for counting, i.e. there may not be any input 0 or 1 to start counting from.


Solution

  • It is not clear what the problem is that you encounter as you state that it is a given that:

    The first input value will contain the number of values

    This number will be your counter.

    You write:

    There may not be any input 0 or 1 to start counting

    You don't need that as input. Your program can have DAT entries, where you do have the possibility to store such a counter, and initialise it as 0 or 1 even before the program runs. But in this particular case, it may be easier to count-down (not up), using the first input as initial value of your counter.

    So, the first task of the program is to read that number. It can then store that as a counter (and liberate the accumulator) and then start reading the remaining values. Before reading each next input, the program will decrease the counter and verify whether it is still not zero.

    Here is how the LMC code could look:

    #input: 5 10 20 30 40 50
    START     INP          // Number of values
         LOOP BRZ FINISH   // No more values? Finish
              SUB ONE      // Decrement counter
              STA COUNT
              INP          // Read next number from input
              ADD SUM      // and add it to the 
              STA SUM      // sum.
              LDA COUNT    // Get counter
              BRA LOOP
       FINISH LDA SUM      // Output the sum
              OUT
              HLT
          ONE DAT 1
        COUNT DAT
          SUM DAT 0
    
    <script src="https://cdn.jsdelivr.net/gh/trincot/[email protected]/lmc.js"></script>