D. Tunus
D. Tunus

Reputation: 271

How can I make loops in Little Man Computer for a Fibonacci Sequence?

        INP
        STA numOne
        OUT
        INP
        STA numTwo
        OUT
        LDA numOne
        ADD numTwo
        STA numThree
        OUT
        LDA numTwo
        ADD numThree
        STA numFour
        OUT
        LDA numThree
        ADD numFour
        STA numFive
        OUT
        LDA numFour
        ADD numFive
        STA numSix
        OUT
        LDA numFive
        ADD numSix
        STA numSeven
        OUT
        LDA numSix
        ADD numSeven
        STA numEight
    OUT
        LDA numSeven
        ADD numEight
        STA numNine
    OUT
        LDA numEight
        ADD numNine
        STA numTen
        OUT
numOne  dat
numTwo  dat
numThree dat
numFour dat
numFive dat
numSix  dat
numSeven dat
numEight dat
numNine dat
numTen dat

I am using the following code in Little Man Computer to output the first 10 Fibonacci sequence terms, however I need to make a loop out of this, which will let me control the amount of iterations I want to be outputted.

From my understanding, I'd guess I would have to input 3 numbers - two of them being the first Fibonacci sequence terms, the third one being the amount of iterations I want to be outputted. But how can I achieve this?

Upvotes: 1

Views: 2110

Answers (1)

EncryptedCamel
EncryptedCamel

Reputation: 302

The fibonacci series can be printed in the LMC in the following manner:

      INP
      STO   n     #number of terms
      LDA   one
      OUT

loop  LDA   fib     #THE MAIN LOOP THAT PRINTS FIBONACCI NUMBERS
      STO   temp2
      ADD   temp
      STO   fib
      LDA   temp2
      STO   temp
      BR    check

check LDA   n         #LOOP TO KEEP A TRACK OF NUMBER OF TERMS
      BRZ   halt
      SUB   one
      STO   n
      BRZ   halt
      LDA   fib
      OUT
      BR    loop

halt  HLT        
n     DAT   000
fib   DAT   001
temp  DAT   001
temp2 DAT   000
one   DAT   001

Explanation: The program first asks for an input n, the number of terms to be printed.Then the loop starts running - it will print the default value of variable fib, which has been set to 1. The value of fib is stored in another variable temp2, and the variable temp is used to record the previous value of fib so that the numbers are added correctly and a correct sequence is obtained. The loop controls the values of fib, temp and temp2 as the number of terms are increased.

The program then checks if the number of terms required have been printed and decrements the value of n. If n=0 it means that the required number of terms has been reached and the program halts. If n is not zero, the loop continues till n=0.

**Though there might me more efficient methods, however this one works correctly and uses a pretty less number of mailboxes which makes it quite efficient.

Upvotes: 2

Related Questions