Question: Write an MIPS program to compute three sums: 1 + 2 + 3 + 4 + ... + 99 + 100 # all values 1100
Write an MIPS program to compute three sums:
1 + 2 + 3 + 4 + ... + 99 + 100 # all values 1100
1 + 3 + 5 + 7 + ... + 97 + 99 # all odd values 1100
2 + 4 + 6 + 8 + ... + 98 + 100 # all even values 1100
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?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
