Hemlata
Hemlata

Reputation: 65

How to find the sum of odd numbers in LMC

I am learning LMC, but I am not able to find the sum of odd numbers till 100 in LMC such as 1+3+5+7... and so on

I did write the code to add the two numbers

  INP //here I wil input 1
  STA 99
  INP // here I will input 2
  ADD 99
  OUT
  HLT

I am not sure how to loop through it, so I can get sum of odd numbers. If someone could please help me?

Upvotes: 0

Views: 1824

Answers (1)

trincot
trincot

Reputation: 350335

If you need to output the odd numbers between 1 and 100, then there is no reason to ask the user for input: you have all elements for solving the problem already, so no need to ask anything.

With LMC you often need to define some constant data, like ... the number 1. And for this exercise, the number 2 would also be handy to have prepared. So reserve two "mailboxes" for these two numbers (use DAT).

Here is how the program could iterate over the odd numbers between 1 and 99:

LOOP      LDA CURRENT  // start with one
          OUT          // output less than 100
          ADD TWO
          STA CURRENT
          SUB HUNDRED  // compare with 100
          BRP EXIT     // halt when above
          BRA LOOP     // and repeat
     EXIT HLT
  CURRENT DAT 1
      TWO DAT 2
  HUNDRED DAT 100

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

However, to calculate the sum of those numbers would exceed the capabilities of the LMC. The sum of 1+3+5+..+99 is 2500, while the LMC can only deal with numbers up to 999, so that is not going to work.

Upvotes: 0

Related Questions