Hema T.

asked • 11/11/23

Lc3 code for fibonacci recursive

LC3 code for the following Fibonacci equivalent that should be called from 

 

int fib(int n) {

  int a, b;

 

 

  if (n <= 0) {

    return 0;

  }

  else if (n == 1) {

    return 1;

  }

  else {

    a = fib(n - 1);

    b = fib(n - 2);

    return a + b;

  }

}


· You may not alter the existing function MAINFN in main.asm.


For example:

Enter an integer: 6

f(6) = 8

 

MAINFN below:


    .ORIG x3000

; int main(void)

; NOTE: Do not alter this function.

MAINFN LD R6, INITSP ; Init. the stack pointer.

    ADD R5, R6, #-1 ; Init. the frame pointer.

    ADD R6, R6, #-1 ; Push space for "n".

    LEA R0, PROMPT ; Print the prompt.

    PUTS

    GETC      ; Read an integer.

    OUT

    LD R1, INTNEG

    ADD R0, R0, R1

    STR R0, R5, #0 ; Assign the integer to "n".

    GETC      ; Consume the newline.

    OUT

    LDR R0, R5, #0 ; Push "n".

    ADD R6, R6, #-1

    STR R0, R6, #0

    LD R4, FIBFN

    JSRR R4    ; Call "fib".

    LDR R1, R6, #0 ; Pop the return value.

    ADD R6, R6, #1

    ADD R6, R6, #1 ; Pop "n".

    LEA R0, RES1  ; Print the result.

    PUTS

    LD R2, INTPOS

    LDR R0, R5, #0

    ADD R0, R0, R2

    OUT

    LEA R0, RES2

    PUTS

    ADD R0, R1, R2

    OUT

    LD R0, NEWLINE

    OUT

    ADD R6, R6, #1 ; Pop "n".

    HALT

INITSP .FILL xFE00

PROMPT .STRINGZ "Enter an integer: "

RES1  .STRINGZ "f("

RES2  .STRINGZ ") = "

INTPOS .FILL x30

INTNEG .FILL x-30

NEWLINE .FILL x0A

FIBFN .FILL x4000

    .END

 

1 Expert Answer

By:

Joseph B. answered • 08/02/25

Tutor
New to Wyzant

B.S. Computer Engineering | Robotics Lead and Research Assistant

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.