MIPS prog. example: Sum of Odd

advertisement
MIPS Programming Example:
Sum of Odd Numbers
Write the MIPS assembly language to compute the sum of odd numbers up to the largest odd
number smaller than or equal to n,
e.g,. 1 + 3 + 5 + ... + n
(or n-1 if n is even)
Assume Register 4 contains n, a positive integer.
Put the output in Register 2.
Let:
Register 8 = sum
Register 9 = next odd number that we need to add
Register 10 = flag indicating whether all odd numbers up to n have been added
begin:
addi $8, $0, 0
addi $9, $0, 1
# initialize sum to 0
# set first odd number to add = 1
loop:
slt
bne
add
addi
j
$4, $9
$0, finish
$8, $9
$9, 2
# check if the odd number is less than n
# if odd number is greater than n then exit
# update sum
# get next odd number
# repeat the summing process
finish:
add $2,
$8,
# put sum in output register
$10,
$10,
$8,
$9,
loop
$0
Download