Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a MIPS assembly language program that prompts for an unsigned integer n, c

ID: 3559715 • Letter: W

Question

Write a MIPS assembly language program that prompts for an unsigned integer n, calls a subroutine that calculates the nth Fibonacci number F (http://en.wikipedia.org/wiki/Fibonacci_number) and then prints out the result on the screen. Example: input n = 0, F =0; n = 1, F = 1; n = 2, F = 1;...; n = 8, F = 21; ..... The output should give enough information about what does the program displays. Submit your work as a zip file containing source code and a screenshot of MARS running the program and displaying the result for a few test input numbers.

Explanation / Answer

This is the "C" code for the question

#include<stdio.h>
int fib(int n)
{
   if (n <= 1)
      return n;
   return fib(n-1) + fib(n-2);
}

int main ()
{
int n = 9;
printf("%d", fib(n));
getchar();
return 0;
}

Now for the ASM- It should look like this-

fib(int):                                # @fib(int)
   pushq   %rbp
   movq   %rsp, %rbp
   subq   $16, %rsp
   movl   %edi, -8(%rbp)
   cmpl   $1, -8(%rbp)
   jg   .LBB0_2
   movl   -8(%rbp), %eax
   movl   %eax, -4(%rbp)
   jmp   .LBB0_3
.LBB0_2:
   movl   -8(%rbp), %eax
   subl   $1, %eax
   movl   %eax, %edi
   callq   fib(int)
   movl   -8(%rbp), %edi
   subl   $2, %edi
   movl   %eax, -12(%rbp)         # 4-byte Spill
   callq   fib(int)
   movl   -12(%rbp), %edi         # 4-byte Reload
   addl   %edi, %eax
   movl   %eax, -4(%rbp)
.LBB0_3:
   movl   -4(%rbp), %eax
   addq   $16, %rsp
   popq   %rbp
   ret

main:                                   # @main
   pushq   %rbp
   movq   %rsp, %rbp
   subq   $16, %rsp
   movl   $0, -4(%rbp)
   movl   $9, -8(%rbp)
   movl   -8(%rbp), %edi
   callq   fib(int)
   leaq   .L.str, %rdi
   movl   %eax, %esi
   movb   $0, %al
   callq   printf
   movl   %eax, -12(%rbp)         # 4-byte Spill
   callq   getchar
   movl   $0, %esi
   movl   %eax, -16(%rbp)         # 4-byte Spill
   movl   %esi, %eax
   addq   $16, %rsp
   popq   %rbp
   ret

.L.str:
   .asciz   "%d"

If tis is not exactly correct- Modify the "C" code to get the desired output then run it through GCC explorer- http://gcc.godbolt.org/ <== note you may change compiler options and desired compiler to get desired code

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote