Skip to content
UoL CS Notes

Loops

COMP124 Lectures

Iteration can be achieved by jumping backwards in the code.

We need to ensure that we don’t end up in an infinite loop. A while loop simply repeat while a given condition is true.

while Loops

This codes calculates the 1000th Fibonacci number:

while (fib2 < 1000) {
	fib0 = fib1;
	fib1 = fib2; 
	fib2 = fib1 + fib0;
}

This is the equivalent assembly code:

while1:
	mov eax, fib2
	cmp eax, 1000	; compare for condition
	jge end_while	; jump out of loop if condition is met
	mov eax, fib1
	mov fib0, eax
	mov eax, fib2
	mov fib1, eax
	add eax, fib0
	mov fib2, eax
	jmp while1		; jump back to start of loop
end_while:
	...

do-while Loops

This is the same code using a do-while loop:

do {
	fib0 = fib1;
	fib1 = fib2; 
	fib2 = fib1 + fib0;
} while (fib2 < 1000);

And the same code in assembly:

do-while:
	mov eax, fib1
	mov fib0, eax
	mov eax, fib2
	mov fib1, eax
	add eax, fib0
	mov fib2, eax
	cmp eax, 1000
	jl do-while
end_while:
	...

This code is more efficient than the last implementation as fib2 is already in the accumulator for the comparison.

for Loops

A counting loop can be implemented in almost exactly the same way as a while loop:

for (int x = 1; x <= 10; x++) {
	y = y + x;
}

Attempt 1

	mov eax, 1	; use eax as x var
floop:			; start of for loop
	add y, eax	; update y
	inc eax		; x++
	cmp eax, 10
	jle floop	; end when eax = 11

Attempt 2

We can improve by counting in reverse:

	mov eax, 10	; start at 10
floop:			; start of for loop
	add y, eax	; update y
	dec eax		; x--
	jnz floop	; end at zero

Attempt 3 - ecx and loop

The ecx register is the counter register and often used in loops.

In can be used iwth special jump instructions:

  • JECXZ - Jump is ecx is zero.
  • JCXZ - Jump is cx is zero.

It can also be used with the loop instruction:

loop <lab>	; decrement ecx
			; jump to <lab> if ecx not zero

So, general form to repeat a statement $n$ times:

	mox ecx, n
L1:	code for statement
	loop L1

This would give the following for the example:

	mov ecx, 10	; use ecx as x var
floop:
	add y, ecx	; update y
	loop floop	; loop back to floop if ecx not zero

This saves another instruction.