Assignment4 Winter2024 Sol
Assignment4 Winter2024 Sol
Your Information:
First Name:
Last Name:
Student ID:
Grade:
Question 1 Grade
Write code to calculate the greatest common divisor (gcd) using ARM assembly language. The 20
first parameter a and the second parameter b are available in memory in the locations opa and
opb respectively. Save the result to a memory location whose address is gcd.
.global main
.text
main:
LDR R0, =opa @ Load the address of opa into R0
LDR R1, =opb @ Load the address of opb into R1
@ Euclidean algorithm
LDR R0, [R0] @ Load the value of a from memory into R0
LDR R1, [R1] @ Load the value of b from memory into R1
gcd_loop:
CMP R1, #0 @ Check if b is equal to 0
BEQ gcd_end @ If b is 0, exit the loop
gcd_end:
MOV R2, R0 @ Move the final value of a (gcd) to R2
1
LDR R0, =gcd @ Load the address of gcd into R0
STR R2, [R0] @ Store the gcd value to the memory location
Here: b Here
.data
opa: .word 48 @ First parameter a
opb: .word 36 @ Second parameter b
gcd: .space 4 @ Memory location to store the result
Question 2 Grade
Write ARM assembly code to calculate the Fibonacci sequence. The main function calls the fibo 40
function to calculate the Fibonacci sequence up to the nth element. The value n is loaded into
R0 as the parameter for the fibo function. Save the final result in R0.
.global main
.text
main:
MOV R0, #10 @ Set the value of n (number of elements)
BL fibo @ Call the fibo function
Here: B Here
fibo:
PUSH {R1} @ Save R1 on the stack
fibo_end:
POP {R1} @ Restore R1
BX LR @ Return to the calling code
.end
2
Question 3 Grade
Write a subroutine STRCAT to concatenate two strings in ARM assembly language. The main 40
program passes the addresses of both strings by registers to the subroutine. The second string
is concatenated to the first string. The addresses of the strings are str1 and str2 and the
address of the new string is str3.
.global main
.text
main:
LDR R0, =str1 @ Load the address of str1 into R0
LDR R1, =str2 @ Load the address of str2 into R1
LDR R2, =str3 @ Load the address of str3 into R2
BL STRCAT @ Call the STRCAT subroutine
B.
STRCAT:
PUSH {LR, R0, R1, R2} @ Save the return address, R0, R1, and R2 on the stack
@ Store the null terminator at the end of the concatenated string (str3)
STRB R3, [R1]
POP {R2, R1, R0, PC} @ Restore R0, R1, R2, and the return address to return
; note we can use BX LR instead of POP{PC}
.data
str1: .asciz "Hello, "
str2: .asciz "world!"
str3: .space 100 @ Reserve space for the concatenated string
3