Loops in MIPS

Use `beq`, `bne`, and `j`, just as for conditional statements.

Example:

Assume that `\$s0` = i, `\$s1` = n, `\$s2` = A, `\$s3` = sum, and that A is an array of `int`.
```	C					FORTRAN
-------					-------

sum = 0;				SUM = 0
i = 0;					I = 0
while ( i < n )			LOOP:	IF ( I .GE. N ) GOTO END
{              				SUM = SUM + A[I]
sum += A[i]; 			I = I + 1
i++; 				GOTO LOOP
}         			END:	...

```

```

move \$s3, \$zero		# sum = 0
move \$s0, \$zero		# i = 0
LOOP:	slt \$t0, \$s0, \$s1	# t0 is 1 if i < n; 0 if i >= n
beq \$t0, \$zero, END	# goto END if i >= n
sll \$t0, \$s0, 2  	# t0 = i * 4
lw \$t1, 0 (\$t0)		# t1 = A[i]
add \$s3, \$s3, \$t1	# sum += A[i]
addi \$s0, \$s0, 1	# i += 1 (or i++)
j LOOP
END:	...

```

Squeezing out every ounce of efficiency:

• How many instructions get executed in the fragment above if n = 100?
2 instructions above the loop, plus 100 * 8 instructions in the loop, plus the two instructions at the top of the loop that get executed when i == n, so 804.
• Could a compiler produce this code differently to make it even more efficient?
```

move \$s3, \$zero		# sum = 0
move \$s0, \$zero		# i = 0
j TEST                  # go to loop test
LOOP:	sll \$t0, \$s0, 2  	# t0 = i * 4