I have recently started learning the Mips assembly language and was on its basics. I had a few pronlems in finding the mean of my program in mips. Can someone help me out by explaining to me the instructions used to find out the mean. An example of the code would be much appreciated.
2 Answers
I can provide you with a sample code. The useful information is being told through comments in the code below. I hope this would be of some help.
.data
arr: .word 1, 2, 3, 4, 5, 6, 7 arrLen: .word 7 avg: .asciiz "\nAverage: "
.text .globl main
main:
la $t0, arr #array is stored
lw $t1, arrLen #array length stored
li $t2, 0
li $t3, 0
loop: #loop for the sum
sltiu $t7, $t2, 7 #should be run uptil 7 since its the array length
beq $t7, $0, stop
lw $t4, ($t0)
addu $t3, $t3, $t4
addiu $t0, $t0, 4
addiu $t2, $t2, 1
j loop
stop:
la $a0, avg
li $v0, 4
syscall
div $t5, $t3, $t1 #average is taken out using the sum calculated above
move $a0, $t5 #value moved to a0 register to be printed
li $v0, 1
syscall
li $v0, 10
syscall #end
.data
size: .word 0 to_store: .word 0 sum: .word 0 avg: .word 0
size_prompt: .asciiz "Enter number of elements: " element_prompt: .asciiz "Enter an element: " msg_space: .asciiz " "
.text
.globl main
main:
# Prints prompt
la $a0,size_prompt
addi $v0,$0,4
syscall
# Gets input from user
addi $v0,$0,5
syscall
sw $v0,size
addi $t0,$0,0
# Creates the list
lw $s0,size
addi $t1,$0,4
mult $s0,$t1
mflo $t2
add $a0,$t1,$t2
addi $v0,$0,9
syscall
stack: beq $t0,$s0,list_sum
# prompt user for list element
la $a0,element_prompt
addi $v0,$0,4
syscall
# read in element value
addi $v0,$0,5
syscall
sw $v0,to_store
lw $t5,to_store
# push element to stack
addi $sp,$sp,-4
sw $t5,0($sp)
addi $t0,$t0,1
j stack
# get sum of array elements
list_sum: beq $s0,0,average # at end? if yes, fly lw $t6,sum # get previous sum lw $t7,0($sp) # get next array element value addi $sp,$sp,4 # advance array pointer add $t6,$t7,$t6 # sum += array[i] sw $t6,sum # store it addi $s0,$s0,-1 # bump down the count j list_sum
average: lw $t0,sum # get the sum
# print the sum
li $v0,1
move $a0,$t0
syscall
# NOTE/FIX: restore the count value
lw $s0,size
div $t0,$s0 # divide by count
mflo $t0
sw $t0,avg # store average
li $v0,4
la $a0,msg_space
syscall
# print average
lw $a0,avg
addi $v0,$0,1
syscall
exit: li $v0,10 # exit program syscall