Skip to content

A3 - Branching in Assembly Language

In assembly language, we can add labels to essentially "bookmark" certain places in the code:

start:
set r1, 2
set r2, 5

middle:
add r3, r1, a2

end:
out r3

A label is just a word followed by a colon, as seen above with start:, middle: and end:.

Labels are useful when used with branching instructions. Our emulator has two such instructions:

  • beq r1, r2, my_label - jumps to my_label if r1 and r2 are equal
  • bne r1, r2, my_label - jumps to my_label if r1 and r2 are not equal

Consider this code in Python, which prints the values 0, 1, 2:

for i in range(3):
    print(i)

The assembly language equivalent is

set r1, 0   # Counter
set r2, 1   # Incrementer
set r3, 3   # Ender

loop:
out r1
add r1, r1, r2
bne r1, r3, loop

Hint - Jumping Unconditionally

Most assembly languages have a jump instruction that can be used to jump to a label unconditionally. I forgot to add this feature to the emulator, but the workaround would be something like this:

# Set r14 and r15 both to zero, and keep them that way
set r14, 0
set r15, 0

# Jump to a label unconditionally this way:
beq r14, r15, my_label

Your Task

Program 1

Update the example above, so that it starts at 10, increments by fives, and stops before reaching 50. The Python equivalent would be:

for i in range(10, 50, 5):
    print(i)

Program 2

Create an assembly language program equivalent to this Python code:

x = 3
y = 3

if x == y:
    print(1)

In your program, you will have two registers to represent the x and y values. The behaviour of your program should update accodingly if x and y held different numbers.

Hint - Consider adding a label to the very end of your program called end:, and including logic to branch to that label, therefore skipping the out instruction, only when the two registers are NOT equal.

Program 3

Create an assembly language program equivalent to this Python code:

x = 3
y = 3

if x == y:
    print(1)
else:
    print(0)

Be sure to test this in scenarios where the registers holding the x and y values are both equal and not equal, to ensure both possible pathways in this program work.

Extension

Create your own program that includes branching. There would be various levels of "extension" possible here depending on how complex you choose to go.