Take rand integer elements to array and display. MIPS.
#MIPS assembly
.data
range: .byte 50
size: .byte 20
.align 4
array: .space 20
# code segment
.text
.globl main
main:
# Take rand integer elements to array
la $s0, array # array[0] address
la $s1, size
lb $s1, ($s1) # array size (counter)
loop:
beq $s1, $0, done # IF(counter==0) goto done
jal GenerateRand # ELSE function GenerateRand
sw $v0, 0($s0) # store rand integer to array
addi $s0, $s0, 4 # next address in array
addi $s1, $s1,-1 # counter--
j loop
done:
la $a0, array # begining address in array
la $a1, size
lb $a1, ($a1) # array size
jal PrintArr # call PrintArr Function.
final:
li $v0, 10 # finished .. stop .. return
syscall # make the syscall
#***************************************
# Function Generate random number
#***************************************
GenerateRand:
lb $a1, range # upper bound of range of returned values
subi $a1, $a1, 1 # Subtract 1 to range
li $v0, 42 # Generate random number
# $a0 contains random
syscall # make the syscall
addi $a0, $a0, 1 # Add 1 (range 1 to [range-1])
add $v0, $0, $a0
jr $ra # jump to parent call
############################################
# function PrintArr
# input: $a0 array address
# $a1 array size
############################################
PrintArr:
addi $sp, $sp, -8 # make space on stack to store registers
sw $s1, 4($sp) # save $s1 on stack
sw $s0, 0($sp) # save $s0 on stack
li $t0,0 # counter array elements
add $s0,$0, $a0 # $s0 = begining array address
add $s1,$0, $a1 # size
Print:
slt $t7, $t0, $s1 # IF(i < size) continue
beq $t7, $zero, endPrint # ELSE goto end print
li $v0, 1 # print integer from $a0
lw $a0,0($s0) # load a[i] to $a0
syscall # make the syscall
li $v0,11 # print char
li $a0,' ' # space
syscall # make the syscall
addi $t0, $t0, 1 # counter++
addi $s0, $s0, 4 # next address in array
j Print
endPrint:
lw $s0, 0($sp) # restore $s0 from stack
lw $s1, 4($sp) # restore $s1 from stack
addi $sp, $sp, 8 # deallocate stack space
jr $ra
Comments
Leave a comment