Write an MIPS program to compute three sums: 1 + 2 + 3 + 4 + ... + 99 + 100 # al
ID: 3888352 • Letter: W
Question
Write an MIPS program to compute three sums:
1 + 2 + 3 + 4 + ... + 99 + 100 # all values 1…100
1 + 3 + 5 + 7 + ... + 97 + 99 # all odd values 1…100
2 + 4 + 6 + 8 + ... + 98 + 100 # all even values 1…100
Do this by using the blt macro (branch if less than).
Use a register (say $t0) for the sum of evens, a register (say $t1) for the sum of odds, and another (say $t2) for the sum of all numbers.
Do this with only one counting loop. The loop body will contain the logic to add the count to the proper sums.
Don't use division to check odd or even, it is not necessary. A bitwise instruction is enough.
This program will not do any I/O. It is just a regular looping exercise. Stop the program with a syscall with 10 in $v0.
Here is the solution I came up with so far, but I have been unable to get the correct sum of all values (I only got the correct sum of even and odd values):
.text
.globl main
main:
ori $t0, $zero, 0 # Initialize register $t2 to contain the sum of even values.
ori $t1, $zero, 0 # Initialize register $t2 to contain the sum of odd values.
ori $t2, $zero, 0 # Initialize register $t2 to contain the sum of all values.
ori $t3, $zero, 1 # Initialize register $t3 to be the counter.
ori $t4, $zero, 101 # Initialize register $t4 to mark the end of the sequence.
loop:
and $t5, $t3, 1
bnez $t5, odd
beqz $t5, even
odd:
add $t2, $t2, $t3
add $t1, $t1, $t3
addi $t3, $t3, 1
blt $t3, $t4, loop # if ($t3 < $t4) Branch to loop
b end
even:
add $t2, $t2, $t3
add $t0, $t0, $t3
addi $t3, $t3, 1
blt $t3, $t4, loop # if ($t3 < $t4) Branch to loop
b end
end:
li $v0, 10 # Terminate the program.
syscall
For the sum of all values, when adding counter to the sum of all values and incrementing the counter and after branching back to loop after the first iteration, the value of the counter is added to the sum of all values, which ends up giving me the wrong result at the end. How can I fix this?
Explanation / Answer
Following is the code for above scenario:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.