Loops


As with conditionals, it is necessary to build loops with branch statements. Here are some examples.

 
Java
 
MIPS
i = 1;
while (i < 10) {
   .
   .
   .
   i++;
}
     li    $t0,0                #  $t0 holds i, i = 0
     li    $t1,10               #  $t1 holds loop limit (10)
while:
     beq   $t0,$t1,loopend      #  i == 10? exit loop
     .
     .
     .
     addi  $t0,$t0,1            #  i++
     b     while                #  branch back to top of loop
loopend:
for (i = 100; i > 0 ; i = i-2) {
   .
   .
   .
}
     li    $t0,100              #  $t0 holds i, i = 100
for:
     beqz  $t0,loopend          #  i == 0? exit loop
     .
     .
     .
     addi  $t0,$t0,-2           #  i=i-2
     b     for                  #  branch back to top of loop
loopend:
while (i < j + 1) {
   .
   .
   .
}
#  assume j is in $t1
#  assume i is in $t2
while:
     addi  $t3, $t1, 1          #  $t3 = j + 1
     bge   $t2,$t3,loopend      #  i >= j + 1? exit loop
     .
     .
     .
     b     while                #  branch back to top of loop
loopend:


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2009