Search Array in ARM Assembly
You need to write a small program in ARM assembly that allows the user to enter an array and to search it. The program should take a list of 10 integers and store them in an array, once the array is entered you should enter a value to search for. The program should report the first index where the item is found, or none if the value is not found. For more assembly language programming assignments contact us for a quote.
Solution:
@simpleprogram.s
@Data Section
.data
promptArray: .asciz “Please enter array: ”
promptKey: .asciz “Please enter key: ”
resultMsg: .asciz “The key is found at index: ”
notFoundMsg: .asciz “none”
format: .asciz “%d”
nl: .asciz “\n”
@ space to save the array
array: .word 0,0,0,0,0,0,0,0,0,0
key: .word 0
@Code Section
.text
.global main
.extern printf
.extern scanf
main:
push {ip, lr}
ldr r0, =promptArray @ ask user to enter the array
bl printf
ldr r4,=array @ load array address in r4
ldr r5,=10 @ count 10 numbers
rdloop:
ldr r0,=format @ format to read an integer
mov r1, r4 @ get current address in array
bl scanf @ read a number
add r4, #4 @ advance to next space in array
adds r5, #-1 @ decrement counter
bgt rdloop @ repeat while not zero
ldr r0, =promptKey @ ask user to enter the key
bl printf
ldr r0,=format @ format to read an integer
ldr r1,=key @ get key address to save read number
bl scanf @ read a number
ldr r0,=key @ pass key value as first argument
ldr r0, [r0]
ldr r1,=array @ pass array address as second argument
bl search @ search for key in the array
mov r4, r0 @ save result in r4
ldr r0, =resultMsg @ print the result message
bl printf
cmp r4, #255 @ compare result with 255 to see if key was found
beq keyNotFound @ if not found, jump to keyNotFound
keyFound: @ else, key was found
ldr r0, =format @ print the index
mov r1, r4
bl printf
b done
keyNotFound: @ if not found
ldr r0, =notFoundMsg @ print “none”
bl printf
done:
ldr r0, =nl @ print a newline
bl printf
pop {ip, pc}
@ Procedure that searches a key in the array
@ On entry:
@ R0 = key to search
@ R1 = pointer to start of array
@ On return:
@ R0 = index in array if found, 255 if not found
search:
push {lr}
ldr r2,=0 @ r2 will be the array index
srchloop:
ldr r3, [r1, r2, lsl #2] @ load a value from the array
cmp r3, r0 @ see if the value is equal to the key
beq found @ if so, go to found to return index
add r2, #1 @ advance to next space in array
cmp r2, #10 @ see if we have searched 10 values
blt srchloop @ if we are below 10, repeat
notfound: @ if we get here, key was not found
mov r0, #255 @ return 255 to indicate value was not found
b return @ jump to function return
found:
mov r0, r2 @ put the current index in r0 for returning it
add r0, #1 @ add 1 to use base 1 indexing
return:
pop {pc} @ return