Ok I have done the fibonacci number iteratively but now I want to do it recursively. I am using CPUSims 3.6.9 16-bit (4 bit opcode).
;getN
;get a value, n, from user
;test if fib(0) or fib(1) return to main with value
getN: read ;read a value and store into accumulator
store n ;store the accumulator value to storage n
jmpz print0 ;jump to location print0 if acc=0
load n ;load n to accumulator
subtract n1 ;acc=acc-1
jmpz print1 ;jump to location print1 if acc=0
store n ;update n
load prevPrev ;load fibonacci(0) to acc
push ;push acc to stack
load prev ;load fibonacci(1) to acc
push ;push acc to stack
;fib
;initial value is 0 and 1
;then as n decrease the fib(n) increases
fib: load prev ;load fibonacci(1)/prev to acc
add prevPrev ;acc=acc + fibonacci(0)/prevPrev
store result ;store acc to storage result
load prev ;load prev/fibonacci(1)
store prevPrev ;store acc=prev to prevPrev
load result ;load result to acc
push ;push acc to stack
store prev ;store result to prev
load n ;load n to acc
subtract n1 ;acc=acc-1
store n ;update n at storage n
jmpz main ;jump to location if acc=0
call fib ;call the fib function recursively
;main subprogram
;pop the top value from stack
;outputs the value
;end the program
main: pop ;pop out the top value from the stack to acc
write ;output the acc
stop ;stop the program
;subprogram for printing fib(0)
print0: load prevPrev ;load fib(0) to acc
write ;output the acc value/fib(0)
stop ;stop the program
;subprogram for printing fib(1)
print1: load prev ;load fib(1) to acc
write ;output the acc value/fib(1)
stop ;stop the program
;storage begin
n: .data 2 0 ;storage n value to find the fibonacci value of
prev: .data 2 1 ;storage for fib(n-1)
prevPrev:.data 2 0 ;storage for fib(n-2)
result: .data 2 0 ;storage for fib(n)
n1: .data 2 1 ;storage for sentinal value 1
;storage end
The above code is done iteratively. I know call and return would work but how?