Instructions
Objective
Write a program to convert C code into assembly language (recursive function).
Requirements and Specifications
First, make the code in the previous question an actual C program so that it can be compiled and run. Play with it so that you feel comfortable with the logic of the code.
Then implement the code in TTPASM. Note that you need to preserve the actual C code structure, this means you cannot turn it into a non-recursive subroutine. Furthermore, all conventions discussed in class regarding subroutines must be followed. The idea is that I should be able to substitute f with my own code, and main should work. Or, I can substitute main with my own, and f should work.
Attach the source code to write your assembly language assignment program. It should be a text file that the assembler is able to assemble.
Screenshots of output



Source Code
Program in C
#include
#include
uint8_t f(uint8_t n)
{
return (n<2) ? (n) : (f(n-1)+f(n-2));
}
int main()
{
uint8_t x;
x = f(10);
printf("f(10)=%d\n",x);
return 0;
}
Program in assembly language
ldi d,0 // initialize the stack
main:
ldi a,10 // load 10 as argument to function
dec d // allocate space in stack
st (d),a // store argument
ldi a,endProg // return to end prog
dec d // reserving a byte on the stack
st (d),a // store return to the stack
jmpi f // call function f(10)
endProg:
inc d // remove argument from stack
// here, register a has the answer
halt // program end
//Function f(n)
f:
dec d // allocate space in stack
st (d),c // save c in stack
cpr c,d // point to stack with c
inc c // increment to skip c
inc c // point to argument
dec d // allocate space for temporary variable
ldi a,2 // load constant 2
ld b,(c) // load argument
cmp b,a // compare arg n with 2
jsi if // if n < 2, go to if
jmpi else // else, go to else
if:
cpr a,b // return n
jmpi return // go to return
else:
dec b // calculate n-1
dec d // allocate byte in stack
st (d),b // pass n-1 as argument
ldi a,next1 // load return address
dec d // allocate byte in stack
st (d),a // save return address
jmpi f // recurse f(n-1)
next1:
inc d // remove argument from stack
st (d),a // save result in variable
ld b,(c) // reload argument
dec b // calculate n-1
dec b // calculate n-2
dec d // allocate byte in stack
st (d),b // pass n-2 as argument
ldi a,next2 // load return address
dec d // allocate byte in stack
st (d),a // save return address
jmpi f // recurse f(n-2)
next2:
inc d // remove argument from stack
ld b,(d) //load previous result f(n-1) from variable
add a,b // add f(n-1)+f(n-2)
return:
inc d // remove allocated variable
ld c,(d) // load c from stack
inc d // pop value
ld b,(d) // load return address from stack
inc d // pop value
jmp b // return