0

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
Infinity_hunter
  • 157
  • 1
  • 7

2 Answers2

0

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/lmc@v0.7/lmc.js"></script>
trincot
  • 317,000
  • 35
  • 244
  • 286
-1

Indeed i do not understand your question but maybe this simple C# console application can help:

static void Main(string[] args)
{
    string input;
    List<int> data = new List<int>();

    Console.WriteLine("Data Input");

    do
    {
        Console.Write("Input [q to quit]: ");

        if ((input = Console.ReadLine()).ToLower() == "q")
            break;

        try
        {
            data.Add(int.Parse(input));
        }
        catch (Exception)
        {
            Console.WriteLine("Input Error!");
        }
    } while (true);

    int sum = 0;

    foreach (int number in data)
    {
        sum += number;
    }

    Console.WriteLine(sum);
}
sunriax
  • 592
  • 4
  • 16