Language-specific implementation

In MATLAB:

s = 30 # can also be explicitly in loop
for i = 1:s
	# content
end

In Rust, we can annotate our loops with labels:

'outer: loop {
	let mut count = 0;
	loop {
		if count == 2 {
			break 'outer;
		}
		count += 1;
	}
}

Range-based loops

For a data structure with a given size, we often iterate through each element in the structure, i.e.,:

for (auto i = 0; i < list.size(); i++);

Range-based loops are able to iterate through in a succinct way, without us needing to access the size() method. For the same functionality, we use:

  • In C++, we use for (auto i : list), which uses iterators.
  • In Python/Rust, we use for i in list
  • In JavaScript, we use for (let i of list)

Under the hood

In Assembly languages, we make use of conditionals and branches to determine where to go. For example, take this program in C:

int i = 0, n = 25;
do {
	i++;
} while (i < n);

In Nios II:

		movi r7, 1
		movi r8, 25
		andi r9, r0, r9
LOOP:   addi r9, r7, r9
		blt r9, r8, LOOP
AFT:    fever br: fever

Broadly speaking for a program like this:

int a = {1, 2, 0x33, 4, 0x55};
int sum = 0, i;
for (i = 0; i < 5; i++) {
	sum += a[i];
}

We can divide these into a few distinct steps, all of which can be executed with several instructions:

  • Everything before the loop
  • Initial computations i = 0
  • Check the condition i < 5
  • Body of the loop sum += a[i]
  • Post-body computation i++
  • Then we return to the condition; if false we continue to whatever is after the loop
		movi r9, 0
init:   movi r8, 0
cond:   movi r10, 5
		bge r8, r10, after
body:   movia r7, a
        add r13, r8, r8
        add r12, r12, r13
        ldh r11, 0(r12)
        add r9, r9, r11
post:   addi r8, r8, 1
        br cond
 
.data .a: .hword 1, 2, 0x33, 4, 0x55