Loops

In C and Java, we have this convenient shorthand syntax for creating a loop:

for (int i = 0; i < 100; i++) {
	// loop body; maybe we want to print i
	printf("%d", i);
}

In MIPS, we need to construct the loop manually. Thankfully this is still pretty straightforward. First, to manually construct the above loop in C, it would look something like this:


int i = 0;
LOOP:
	// loop condition; check if we should break out of the loop
	if (i < 100)
		goto END_LOOP;

	// loop body; maybe we want to print i
	printf("%d", i);
	
	// loop repeat; increment i and jump back to the start of the loop
	i++;
	goto LOOP
END_LOOP:

Translated to MIPS code, we get something like this:

# C Code:
# 
# for (int i = 0; i < 100; i++) {
# 	// loop body; maybe we want to print i
# 	printf("%d", i);
# }
# 
# Registers used:
#   $t0 : iterator i
#   $t1 : the value 100 that we check against 1
#   $t2 : temp boolean

	# initialize values
	addi $t0, $zero, 0         # t0 = i = 0
	addi $t1, $zero, 100       # t1 = 100
	
LOOP:
	# loop condition; check if we should break out of the loop
	slt  $t2, $t0, $t1
	beq  $t2, $zero, END_LOOP  # if !(i < 100) goto END_LOOP
	
	# loop body; maybe we want to print i
	addi $v0, $zero, 1
	add  $a0, $t0, $zero
	syscall                    # printf("%d", i)
	
	# loop repeat; increment i and jump back to the start of the loop
	addi $t0, $t0, 1           # i++
	j    LOOP                  # goto LOOP
END_LOOP: