Wirte the code in MASM Assembly language code (MPI) Step1: Write an assembly pro
ID: 3764031 • Letter: W
Question
Wirte the code in MASM Assembly language code (MPI)
Step1: Write an assembly procedure which computes the following:
int myfib(n) /* n is a positive integer */
if (n<=3) return 1;
/* else */
return myfib(n-1)+myfib(n-2)+myfib(n-3);
NOTE THAT THE ABOVE FUNCTION IS RECURSIVE. YOUR PROCEDURE NEEDS TO BE RECURSIVE AND COMPUTE EXACTLY AS DESRIBED IN MYFIB(). NO CREDIT WILL BE GIVEN IF YOUR PROCEDURE IS NOT RECURSIVE. NO CREDIT WILL BE GIVEN IF YOUR PROGRAM IS CROSS-ASSEMBLED FROM ANOTHER LANGUAGE.
YOU DECIDE ON WHICH REGISTERS TO USE (FOR PARAMETER PASSING AND RETURNED VALUES, ETC).
Step 2: After completing Step 1, write an assembly program that computes and displays in a separate line the following:
i myfib(i)
for all integer i, from i=1 to 15.
The initial part of the output will look as the following:
1
1
1
3
5
9
17
Explanation / Answer
include Irvine32.inc
.code
main PROC
mov ecx,0
push 10 ; calculate the nth fib
call fib ; calculate fib (eax)
add esp, 4 ; clean up the stack
call WriteDec
call Crlf
exit
main ENDP
fib PROC C
add ecx,1
push ebp
mov ebp,esp
sub esp, 4 ; space for a local dword [ebp-4]
mov eax,[ebp+8] ; get n
; if ((n == 1) || (n == 2)) return 1;
cmp eax,2 ; n == 2?
je exception2
cmp eax,1 ; n == 1?
je exception2
;else return fib(n-1) + fib(n-2);
dec eax
push eax ; Fib(n-1)
call fib
mov [ebp-4], eax ; store first result
dec dword ptr [esp] ; (n-1) on the stack -> (n-2)
call fib
add esp, 4 ; clean up stack
add eax, [ebp-4] ; add result and stored first result
jmp Quit
exception2:
mov eax, 1 ; start values: 1, 1
; dec eax ; start values: 0, 1
Quit:
mov esp, ebp ; restore esp
pop ebp ; restore ebp
ret ; return EAX, stack not cleaned up
fib ENDP
END main
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.