In: Computer Science
Write the following program in MIPS:
a) declare an array A of the following numbers: 3, 5, 8, 10, 12, 2, 76, 43, 90, 44
b) declare a variable called size which stores the number of element in array A, that is 10.
c) write a subroutine to search for a number stored in an array
and return true or false. In C++ the subroutine is as
follows:
search(array, size, number_To_Search)
e.g. search(A, 10, 12)
The subroutine should return 0 for false or 1 for true in register
$v0.
d) The parameters to the search subroutine are stored in
$a0=stores base address of A, $a1=stores the number of elements in
A that is 10, $a2=stores the number to search for (e.g. 12)
e) In C++, you would write:
for (int i=0; i<size; i++)
if A[i] == number_to_search return true;
return false
Your MIPS program is a translation of the C++ code.
f) You can test your program by writing the following
instructions:
la $a0, A
lw $a1, size
addi $a2, $zero, 12
jal search # search for 12 in the array A of size
10
lw $a0, $v0 # subroutine search result is store in $v0;
its value is moved to $a0
lw $v0, 1 # code to print integer value in
$a0
syscall
lw $v0, 10 # code to terminate program
syscall
Given below is the code for the question. Please do rate the answer if it helped. Thank you.
.data
A: .word 3, 5, 8, 10, 12, 2, 76, 43, 90, 44
size: .word 10
.text
la $a0, A
lw $a1, size
addi $a2, $zero, 12
jal search # search for 12 in the array A of size
10
move $a0, $v0 # subroutine search result is store in
$v0; its value is moved to $a0
li $v0, 1 # code to print integer value in $a0
syscall
li $v0, 10 # code to terminate program
syscall
search:
li $t0, 0 #index
li $v0, 0 #set return value to false
loop:
bge $t0, $a1, exit_search
mul $t1, $t0, 4 #to get offset, multiply index by 4
since each integer in the array takes 4 bytes
add $t1, $t1, $a0 #add base address to offset
lw $t0, ($t1)
beq $t0, $a2, found
addi $t0, $t0, 1
b loop
found:
#store 1 in $v0
li $v0, 1
exit_search:
jr $ra
==================================
output
-----
1
-- program is finished running --