&&&&&&&&&&&&&&&&&&&7 Please help me &&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&& By using
ID: 2291344 • Letter: #
Question
&&&&&&&&&&&&&&&&&&&7 Please help me &&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&& By using MIPS assembly code &&&&&&&&
&&&&&&&&&&&&&&&&&&&&&
Find the sum of integers from 1 to 2N-1 where N is a value that you input it from the keyboard
&&&&&&&&&&&&&&&&&&&&&&
Explanation / Answer
High-level code:
int count = 1;
int sum = 1;
while(count<N){
count = count + 4;
sum = sum + count;
}
Associate variable 'count' with register $t0 and
variable 'sum' with register $s0.
Equivalent MIPS code:
addi $t0, $zero, 1
addi $s0, $zero, 1
Loop: slti $t2, $t0, N
beq $t2, $zero, Exit
addi $t0, $t0, 4
addi $s0, $s0, $t0
j Loop
Exit:
.data
array: .word 23,-2,45,67,89,12,-100,0,120,6 # array = {23,-2,45,67,89,12,-100,0,120,6}
length: .word 10 # the length of the array is 10
sum: .word 0 # the sum of the integers (in array) is 0
squareSum: .word 0 # the square sum of the integers (in array) is 0
sumMessage: .asciiz "The sum of the array(sign) is: "
squareMessage: .asciiz "The sum of the squares(sign) is: "
newLine: .asciiz " "
# Algorithm being implemented to sum an array
# sum = 0 (use $t0 for sum)
# squarSum = 0 (use %t5 for squarSum)
# for i = 0 to length-1 do (use $t1 for i)
# sum = sum + array[i] (use $t2 for length-1)
# squareSum = squareSum + array[i]*array[i]
# end for (use $t3 for base addr. of array)
.text
main:
li $t0, 0 # load immediate 0 in register $t0 (sum)
li $t5, 0 # load immediate 0 in register $t0 (squarSum)
la $t3, array # load base addr. of array into $t3
lw $t2, length # load length in register $t2
addi $t2, $t2, -1 # $t2 = length - 1
li $t1, 0 # initialize i in $t1 to 0
loop:
bgt $t1, $t2, exit # exit loop when i > (length-1)
mul $t4, $t1, 4 # multiple i by 4 to get offset within array
add $t4, $t3, $t4 # add base addr. of array to $t4 to get addr. of array[i]
lw $t4, 0($t4) # load value of array[i] from memory into $t4
add $t0, $t0, $t4 # update sum
mul $t6, $t4, $t4 # temp register %t6
add $t5,$t5,$t6 # update squareSum
addi $t1, $t1, 1 # increment i
j loop
exit:
# print sum message
li $v0, 4
la $a0, sumMessage
syscall
# print value of sum
li $v0, 1
addi $a0,$t0,0
syscall
# print new line
li $v0, 4
la $a0, newLine
syscall
# print square sum message
li $v0, 4
la $a0, squareMessage
syscall
# print value of squareSum
li $v0, 1
addi $a0,$t5,0
syscall
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.