Reputation: 521
I'm writing an MIPS program using for-loop to calculate the sum of all odd number from 1 to 10. It should be 25, yet I got 48. I don't know where is the error. Here's my code:
################# Pseudocode #####################
i = 1
n = 10
sum = 0
for(i=1; i<=10; i+=2) {
sum += i;
}
printf("The sum of all odd number from 1 to 10 is: %d", sum);
return 0;
################# Data segment #####################
.data
msg: .asciiz "\ncurrent tally: \n"
################# Code segment #####################
.text
.globl main
main:
li $t0, 1 # temp counter, starts at 1
li $t1, 0 # set to zero, to store sum
add_loop:
bgt $t0, 11, end_loop # break out of loop if counter > 11
addi $t0, $t0, 2 # add 2 in $t0 to skip even num
add $t1, $t1, $t0 # sum += i
li $v0, 4
la $a0, msg
syscall # print out user-friendly msg
li $v0, 1
move $a0, $t1
syscall # print out result from loop
j add_loop
end_loop:
li $v0, 10 # terminate program run and
syscall # exit
The output: current tally: 3 current tally: 8 current tally: 15 current tally: 24 current tally: 35 current tally: 48 -- program is finished running --
Upvotes: 1
Views: 2719
Reputation: 4137
You start your t0
var with 1 and then you add 2 before add $t1, $t1, $t0
, hence the first value to be summed to t1
is 3 and you are missing 1.
Then also since the break condition is >11
, 11 is also summed to t1
.
Finally, you are adding +13 somewhere else as well (maybe it makes a last iteration before breaking the loop?), so -1+11+13 gives you the 23 of difference between 25 and 48.
So probably would be better to do
add_loop:
bgt $t0, 9, end_loop # break out of loop if counter > 9 (so 9 is counted as well!)
add $t1, $t1, $t0 # sum += i
addi $t0, $t0, 2 # add 2 in $t0 to skip even num
Since you already start with t0=1
Upvotes: 2