118k views
4 votes
write a mips assembly language program that can search for a number that entered by user in an array with 20 integer numbers and prints the index of the number in the array if it is found and -1 if not found. you are not reading numbers from keyboard. when declaring the array, initialize it. write the program as a procedure. in main program declare number and array, call linear search procedure. procedure returns index or -1 if not found. print result in main procedure.

User Nanu
by
8.4k points

1 Answer

6 votes

Here's an example MIPS assembly program that implements linear search to find a number entered by the user in an array of 20 integers:

.data

array: .word 4, 5, 8, 9, 1, 3, 10, 7, 6, 15, 20, 11, 14, 12, 16, 19, 2, 18, 17, 13

message1: .asciiz "Enter a number to search for: "

message2: .asciiz "The number was found at index "

message3: .asciiz "The number was not found."

.text

.globl main

# procedure to search for a number in an array

# arguments: $a0 - pointer to the array

# $a1 - size of the array

# $a2 - number to search for

# returns: $v0 - index of the number in the array, or -1 if not found

linear_search:

addi $sp, $sp, -8 # allocate space on the stack

sw $ra, 0($sp) # save the return address

li $t0, 0 # initialize index to 0

loop:

beq $t0, $a1, not_found # if index == size, return -1

lw $t1, ($a0) # load the array element at index i

beq $t1, $a2, found # if element == number, return i

addi $t0, $t0, 1 # increment index

addi $a0, $a0, 4 # advance array pointer

j loop

found:

move $v0, $t0 # set the return value to the index

j done

not_found:

li $v0, -1 # set the return value to -1

done:

lw $ra, 0($sp) # restore the return address

addi $sp, $sp, 8 # deallocate space on the stack

jr $ra # return to the caller

# main program

main:

li $v0, 4 # print message asking for input

la $a0, message1

syscall

li $v0, 5 # read in the number to search for

syscall

move $a2, $v0 # store the number to search for in $a2

la $a0, array # set array pointer in $a0

li $a1, 20 # set array size in $a1

jal linear_search # call linear search procedure

beq $v0, -1, not_found # if return value is -1, print not found message

li $v0, 4 # print found message

la $a0, message2

syscall

move $a0, $v0 # print the index of the number

li $v0, 1

syscall

j done

not_found:

li $v0, 4 # print not found message

la $a0, message3

syscall

done:

li $v0, 10 # exit program

syscall

Note that this program initializes the array with

User Paultechguy
by
7.5k points