In this example, we will write a sample program that will sum all the numbers from 1 to 100
In our case, it is easier to sum from 100 to zero.
This is because the CPU updates a special register call the
Program Status Register with the results of mathematical operations.
We will keep subtracting from a counter register until the Z
flag is set,
telling us the number is zero.
First, we set a register as a counter, equal to 100
MOVS R0, #100
Next, we set our result register to an initial value of zero
MOVS R1, #0
Now we write a loop that
If the counter register is not zero, repeat the loop
loop ADDS R1, R1, R0
SUBS R0, R0, #1
BNE loop ; Branch if Z is not set
Lastly, we run the program and ask for the value in register R1. And if all went well, we should get 5050.
%run
%reg R1
R1: 5050
It is customary to end your program with a
branch to itself to make an infinite loop,
although this is not necessary for IArm.
This is simply done with B .
B .
When run, this will raise an error that we have reached an infinite loop
%run
Error in B: You have reached an infinite loop