04. Loops
- Register planning basics
- Canonical loop flow (see lectures)
- Simple loop: input N, output N*1 N*2 ... N*N
- Long-live vs. temporary registers
- Solution:
1 # input N and output N*1 N*2 … N*N by line 2 li $v0 5 # input N 3 syscall 4 move $t1 $v0 # $t1 is constant N 5 6 # start a loop 7 move $t0 $t1 # $t0 is loop counter, initializing 8 next: blez $t0 done # branch if counter stops 9 10 subu $t2 $t1 $t0 # calculate multiplyer i 11 addiu $t2 $t2 1 12 mult $t2 $t1 # lo is i*N now 13 14 li $v0 1 # print a product 15 mflo $a0 16 syscall 17 li $v0 11 # print a space 18 li $a0 0x20 # 0x20 == 32 == ' ' 19 syscall 20 21 subiu $t0 $t0 1 # changing counter 22 b next 23 done: li $v0 10 # exit 24 syscall
- Nested loop: input N. output
1*1 1*2 ... 1**N 2*1 2*2 ... 2**N ................ N*1 N*2 ... N**N
- Solution
1 # input N and output 2 # 1*1 1*2 … 1*j … 1*N 3 # ................... 4 # i*1 i*2 … i*j … i*N 5 # ................... 6 # N*1 N*2 … N*j … N*N 7 # line by line 8 9 # Register planning: 10 # $t1 — N, $t0 — oute counter, $t3 — innter counter, $t2 — calculated i 11 12 li $v0 5 # input N 13 syscall 14 move $t1 $v0 # $t1 is constant N 15 16 # start an outer loop 17 move $t0 $t1 # initializing outer counter 18 lines: blez $t0 done # branch if i stops 19 20 subu $t2 $t1 $t0 # calculate i 21 addiu $t2 $t2 1 22 23 #start an inner loop 24 move $t3 $t1 # initializing inner counter 25 cells: blez $t3 again # branch if j stops 26 27 subu $t4 $t1 $t3 # calculate j 28 addiu $t4 $t4 1 29 mult $t2 $t4 # calculate i*j (in hi) 30 31 li $v0 1 # print a product 32 mflo $a0 33 syscall 34 li $v0 11 # print a space 35 li $a0 0x20 # 0x20 == 32 == ' ' 36 syscall 37 38 subiu $t3 $t3 1 # change inner counter 39 b cells 40 41 again: li $v0 11 42 li $a0 0xa # 0xa == 20 == '\n' 43 syscall 44 subiu $t0 $t0 1 # change outer counter 45 b lines 46 47 done: li $v0 10 # exit 48 syscall