Reputation: 49
i thought i had an idea how to do it using only add,sub,mult,addi,and,or,andi,ori,lw,sw,beq,bne,slt,slti,mflo.
i have to make sure every detail is in there, the stack pointer is clear etc.
any help solving this please? not for homework, just for studying for a test. i tried working it out and got it wrong, and just want to see a correct solution so i can see what i did wrong. i would ask my professor but he doesn't have office hours today and i need to figure this out tonight since i'm busy for the rest of the week
Upvotes: 0
Views: 1887
Reputation: 2143
There is no real reason to do anything with the stack pointer unless we want to keep something on the stack. However in such a simple program, it's easier to work exclusively with registers. (using only add,sub,mult,addi,and,or,andi,ori,lw,sw,beq,bne,slt,slti,mflo.)
.text
.global main
main:
addi $t0, $zero, 10 # (counter) we will start with 10 and go down to zero
add $t1, $zero, $zero # (sum) our sum, 0
count:
add $t1, $t1, $t0 # sum += counter
addi $t0, $t0, -1 # counter -= 1
bne $t0, $zero, count # if (counter) goto count
add $v0, $zero, $t1 # return value, our sum
#jr $ra # return (jr not allowed?)
If you really wanted to utilize the stack to store the local variables (count and sum), you could do something like this. However, as you can see, it's a quite extensive and unnecessary.
.text
.global main
main:
addi $sp, $sp, -12 # Make room on the stack ($ra, sum, counter)
sw $ra, 0($sp) # save the return address (not really needed)
sw $zero, 4($sp) # sum variable, set to 0
addi $t0, $zero, 10
sw $t0, 8($sp) # counter variable, set to 10
count:
lw $t0, 4($sp) # load sum
lw $t1, 8($sp) # load counter
add $t0, $t0, $t1 # sum += counter
addi $t1, $t1, -1 # counter -= 1
sw $t0, 4($sp) # save the sum value
sw $t1, 8($sp) # save the counter
bne $t1, $zero, count # if (counter) goto count
lw $v0, 4($sp) # return value, the sum
lw $ra, 0($sp) # restore caller's address
addi $sp, $sp, 12 # pop the stack
#jr $ra # return to caller (jr not allowed?)
Upvotes: 1