# For Loop Example # # Complete program: For Loop example on Slides 33 & 34 of 03 MIPS Introduction # .data x: .word 42 y: .word 8 sum: .word 0 answer: .asciiz "The sum is " newline: .asciiz "\n" .text main: # Function prologue -- even main has one subu $sp, $sp, 24 # allocate stack space -- default of 24 here sw $fp, 0($sp) # save caller's frame pointer sw $ra, 4($sp) # save return address addiu $fp, $sp, 24 # setup main's frame pointer # Put x into $s0 la $t0, x lw $s0, 0($t0) # Put y into $s1 la $t0, y lw $s1, 0($t0) # Put the constant 1 into $t1 li $t1, 1 add $s2, $zero, $zero # sum = 0 add $t0, $zero, $zero # i = 0 LoopBegin: slt $t2, $t0, $s1 # is i < y ?? beq $t2, $zero, LoopEnd # branch below end of loop if done add $s2, $s2, $s0 # sum = sum + x add $t0, $t0, $t1 # i++ j LoopBegin LoopEnd: # Print message la $a0, answer li $v0, 4 syscall # Print the sum add $a0, $s2, $zero li $v0, 1 syscall # Print newline la $a0, newline li $v0, 4 syscall done: # Epilogue for main -- restore stack & frame pointers and return lw $ra, 4($sp) # get return address from stack lw $fp, 0($sp) # restore the caller's frame pointer addiu $sp, $sp, 24 # restore the caller's stack pointer jr $ra # return to caller's code