A Level Computer Science · Chapter 5 · Component 01: Computer systems
Underneath every program is machine code, and assembly language writes it as short readable instructions that act directly on registers and memory.
This chapter teaches how to write and trace programs for the Little Man Computer, a simple model of a real processor, with branches for selection and loops. It then teaches the four addressing modes that decide where an instruction finds its data.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- explain the difference between machine code and assembly language, and the job of an assembler
- describe an instruction as an opcode and an operand, and decode a Little Man Computer instruction
- use the LMC instructions ADD, SUB, STA, LDA, BRA, BRZ, BRP, INP, OUT, HLT and DAT
- write and trace LMC programs that use selection and iteration
- explain immediate, direct, indirect and indexed addressing, and find the value each loads
- use indexed addressing to work through an array, and indirect addressing to follow a pointer
Time: three sessions, about 4 hours, plus the programming task.
You need first: the fetch-decode-execute cycle and registers from Processor architecture and performance, and selection and loops from Programming constructs.
The big picture
The big picture
A processor does not understand Python. It understands only binary instructions, each telling it to do one small thing, such as add two numbers or copy a value from memory. A program in a high-level language must be translated into these machine code instructions before it can run.
Writing machine code by hand would mean writing long strings of 0s and 1s. Assembly language replaces each instruction with a short word, called a mnemonic, such as ADD or LDA. Each line of assembly language corresponds to one machine code instruction, so the programmer controls exactly what the processor does.
The Little Man Computer, or LMC, is a simplified model used to learn assembly language. It has 100 memory locations, called mailboxes, a single working register called the accumulator, and a program counter that holds the address of the next instruction. Its eleven instructions are enough to write any algorithm.
The LMC is deliberately simple, but every idea in it is real. Real processors fetch an instruction, decode it into an opcode and an operand, and execute it, just as the LMC does. They branch to make decisions and jump back to make loops, just as LMC programs do.
An instruction's operand does not always hold the data itself. It might be the data, or the address of the data, or the address of the address. These different meanings are called addressing modes. They let one short instruction reach arrays, pointers and constants in the way each task needs.
Assembly language is used where speed, size or direct control of hardware matter most: in device drivers, embedded systems and parts of operating systems. Understanding it also explains what a compiler produces, and why some high-level code runs faster than other code that looks similar.
The LMC is also a stored-program computer. Its instructions and its data sit side by side in the same mailboxes, and nothing but the program counter decides which is which. That is the von Neumann idea behind almost every computer built since the 1940s. It is also why a program that runs into its own data can go badly wrong.
Section 1
Machine code and assembly language
Instructions as numbers
Every machine code instruction is a binary number. Part of it, the opcode, says which operation to carry out. The rest, the operand, gives the data or the address the operation works on. A processor's instruction set is the full list of opcodes it understands.
The LMC writes its instructions in decimal to make them easier to read. Each instruction is a three-digit number. The first digit is the opcode, and the last two digits are the operand, which is a mailbox address from 00 to 99. So 306 means opcode 3, which is STA, with address 06.
Instruction formats in real processors
A real processor stores each instruction in binary, split into fields. In a simple 16-bit format, the first 4 bits might hold the opcode and the remaining 12 bits the operand. Four opcode bits allow 2⁴ = 16 different instructions, and 12 operand bits can address 2¹² = 4,096 memory locations.
That split is a trade-off. More opcode bits give a richer instruction set but leave fewer bits for the operand, so less memory can be addressed directly. Real processors use several formats, and a field of mode bits often says how the operand should be read, which is the subject of section 5.
Assembly language and the assembler
Assembly language gives each opcode a mnemonic, so 306 is written STA 6. It also lets the programmer use labels, such as first, instead of numbered addresses. An assembler is the program that translates assembly language into machine code, replacing every mnemonic with its opcode and every label with its address.
Common mistake: thinking assembly language is the same as machine code. Assembly language is text that people can read, such as ADD 6. Machine code is the binary, or here the number 106, that the processor runs. An assembler translates one into the other, line for line.
Worked example 1: decoding instructions
Decode the LMC instructions 512, 106 and 902.
| Working | Reason |
|---|---|
| 512: opcode 5 is LDA, address 12, so LDA 12 | The first digit gives the operation |
| 106: opcode 1 is ADD, address 06, so ADD 6 | The last two digits give the mailbox |
| 902 is OUT, which needs no address | 901 and 902 are the input and output codes |
| The three instructions are LDA 12, ADD 6 and OUT | Each code stands for one instruction |
Derivation: splitting an instruction into opcode and address
An LMC instruction code holds the opcode in its hundreds digit and the address in its last two digits. So the code is built like this.
Dividing by 100 separates the two parts. The whole-number quotient is the opcode, and the remainder is the address.
For 512, 512 DIV 100 = 5 and 512 MOD 100 = 12, giving LDA 12. A real processor does the same with binary fields, taking the top bits as the opcode and the low bits as the operand.
Why use assembly language?
Programs written in assembly language can be very fast and very small, because nothing is added that the programmer did not write. They can control hardware directly, which is essential for device drivers and for the first code a computer runs when it starts.
The costs are high. Assembly language is slow to write and hard to read, a simple task takes many instructions, and the program only runs on one family of processor. Most software is written in high-level languages, with assembly kept for the small parts where it matters.
Processors are often grouped by the style of their instruction set. A complex instruction set computer, or CISC, has many instructions, some of which do a lot of work in one step. A reduced instruction set computer, or RISC, has fewer, simpler instructions that each take one clock cycle. The LMC, with eleven simple instructions, is very much in the RISC style.
Low-level and high-level languages
Machine code and assembly language are low-level languages: they work directly with the processor's own instructions, registers and memory addresses. High-level languages, such as Python, describe what should happen in terms closer to the problem, and leave the details of registers and addresses to a translator.
One high-level statement usually becomes several assembly instructions. The statement total = total + price might become LDA total, ADD price and STA total. Seeing that link makes clear why high-level programs are easier to write, and why the translator matters so much to their speed.
Assembly language is also how security researchers and debuggers look inside programs. When a program crashes, a debugger can show the exact machine instruction that failed and the values in every register. Being able to read that output is a practical skill, even for programmers who never write assembly themselves.
Check yourself. Decode the instruction 715, and say what it does.
Show the answer
715 has opcode 7, which is BRZ, and address 15. It means BRZ 15: if the accumulator holds 0, the program jumps to mailbox 15; otherwise it carries on with the next instruction.
Section 2
The Little Man Computer
The instruction set
The LMC has eleven instructions. They load and store values, do arithmetic, read input, write output and change the order in which instructions run.
| Mnemonic | Code | What it does |
|---|---|---|
| ADD | 1xx | Add the value in mailbox xx to the accumulator |
| SUB | 2xx | Subtract the value in mailbox xx from the accumulator |
| STA | 3xx | Store the accumulator in mailbox xx |
| LDA | 5xx | Load the value in mailbox xx into the accumulator |
| BRA | 6xx | Branch always: jump to mailbox xx |
| BRZ | 7xx | Branch to xx if the accumulator is zero |
| BRP | 8xx | Branch to xx if the accumulator is zero or positive |
| INP | 901 | Read an input into the accumulator |
| OUT | 902 | Output the accumulator |
| HLT | 000 | Stop the program |
| DAT | Reserve a mailbox for data, with an optional starting value |
Common mistake: confusing STA with LDA. STA stores the accumulator into a mailbox, so it writes to memory. LDA loads a mailbox into the accumulator, so it reads from memory. Mixing them up means values are never saved, or the accumulator is overwritten when it should be kept.
Each instruction does very little on its own. Adding two numbers from the keyboard takes six instructions, because every value must be read, stored, loaded and combined in separate steps. A single line of Python, such as print(a + b), becomes many machine instructions once it is translated.
Reading an instruction table
Most of the instructions with an address work on the accumulator and one mailbox. ADD and SUB change the accumulator using a mailbox's value. LDA replaces the accumulator with a mailbox's value, and STA does the reverse. None of them change the mailbox except STA, which is the only way a program writes to memory.
The three branches never touch the accumulator or memory. They only change the program counter, and only BRA does so every time. INP, OUT and HLT have no address at all, because they always work on the accumulator, the input, the output or the machine itself.
Running a program
The program counter starts at mailbox 0. On each cycle, the LMC fetches the instruction at the address in the program counter, adds 1 to the program counter, decodes the instruction and executes it. A branch instruction works by changing the program counter, so the next fetch comes from somewhere else.
Figure 5.1 runs three LMC programs one instruction at a time. Step through and watch the accumulator, the program counter and the outputs. Then switch on the wrong model, which treats STA as a load.
The Little Man Computer
- Accumulator
- 17
- Outputs so far
- none
- Instructions to halt
- 6
Worked example 2: tracing a program
Trace the adding program from the big picture with inputs 25 and 17.
| Working | Reason |
|---|---|
| INP puts 25 in the accumulator; STA first saves it in mailbox 6 | The first number must be kept safe |
| INP puts 17 in the accumulator, replacing 25 | Each input overwrites the accumulator |
| ADD first adds mailbox 6, so the accumulator holds 42 | The stored 25 is added to 17 |
| OUT outputs 42, then HLT stops after 6 instructions | Every instruction ran exactly once |
Behind the scenes, each step uses more registers than the LMC shows. The program counter's value is copied into the memory address register. The instruction arrives in the memory data register, then is copied into the current instruction register to be decoded. The LMC hides these, so that the accumulator and program counter are the only registers to watch.
A trace table for the LMC is the assembly-language version of the trace tables in Programming constructs. One row per instruction executed, with columns for the accumulator, any mailboxes that change and the output, is the clearest layout. Branches make some rows jump to a new mailbox, which the mailbox column records.
Data and labels
DAT reserves a mailbox for data. It is normally placed after HLT, so the data is never run as an instruction. A label in front of DAT names the mailbox, and DAT 1 gives it a starting value of 1, which is useful as a constant for counting.
Labels make programs readable and easy to change. If a new instruction is added near the start, every mailbox after it moves down one place. With labels, the assembler simply works out the new addresses. With numbered addresses written by hand, every branch and data reference would have to be corrected.
Worked example 3: subtraction and negative results
A program runs INP, STA x, INP, SUB x, OUT, HLT, with x DAT. Trace it with inputs 30 then 50, and with 50 then 30.
| Working | Reason |
|---|---|
| Inputs 30 then 50: x = 30, then 50 − 30 = 20 is output | SUB takes mailbox x from the accumulator |
| Inputs 50 then 30: x = 50, then 30 − 50 = −20 | The result is negative |
| The LMC stores only 000 to 999, so −20 is held as 980 and a negative flag is set | Negative values wrap round from 1000 |
| BRP would treat the result as negative, though 980 is printed | Programs must test before outputting |
An LMC program that runs past its HLT, or branches into its data, will try to execute the data as instructions. A data value of 512, for example, would be run as LDA 12. Placing every DAT line after the last HLT, and making sure every path through the program ends at a HLT, prevents this.
The accumulator as a bottleneck
The LMC has only one register for data, so almost every instruction moves a value into or out of it. Real processors have many general-purpose registers, often 16 or 32, so they can keep several values close at hand without storing them in memory. That is one of the main reasons real code needs fewer memory accesses than LMC code.
Check yourself. After LDA 7, which changes: the accumulator or mailbox 7?
Show the answer
The accumulator changes. LDA 7 copies the value in mailbox 7 into the accumulator, and mailbox 7 keeps its value. STA 7 would do the opposite and change mailbox 7.
Section 3
Selection in assembly language
Branching on a condition
The LMC has no IF statement. Selection is built from a test and a branch. The program subtracts one value from another, leaving a result in the accumulator. BRZ jumps if that result is zero, and BRP jumps if it is zero or positive. If the branch is not taken, the next instruction runs instead.
So to test whether b ≥ a, a program loads b, subtracts a and uses BRP. If b − a is zero or positive, the branch is taken. If it is negative, the program falls through to the next instruction, which handles the other case.
Common mistake: using BRZ where BRP is needed. BRZ jumps only when the accumulator is exactly zero. To test whether one value is at least another, the test must also catch positive results, so BRP is the right branch. Using BRZ sends every strictly larger value down the wrong path.
Other comparisons are built from the same two branches. To test whether a is greater than b, the program can work out b − a. If BRP does not branch, the result was negative, so a is the larger. To test for equality, it subtracts and uses BRZ. Every IF statement in a high-level language becomes a subtraction and a branch like these.
Because the LMC has only one accumulator, each comparison destroys the value it was working on. The program must keep the original values in mailboxes and load them again after the test. That is why the larger-number program stores both inputs before comparing them.
Worked example 4: outputting the larger number
This program outputs the larger of two inputs. Trace it with inputs 12 then 40.
INP
STA a
INP
STA b
SUB a
BRP second
LDA a
OUT
HLT
second LDA b
OUT
HLT
a DAT
b DAT
| Working | Reason |
|---|---|
| a = 12 and b = 40 are stored; the accumulator holds 40 | Both inputs must be kept for later |
| SUB a gives 40 − 12 = 28 | The sign of b − a shows which is larger |
| 28 is positive, so BRP jumps to second | BRP branches on zero or positive |
| LDA b then OUT outputs 40, after 9 instructions | The larger value is printed |
Notice that the program has two HLT instructions, one at the end of each path. Without the first HLT, the program would carry on after outputting a, run LDA b and output b as well. Every path through a program with branches must be checked for where it ends.
Worked example 5: the other path
Trace the same program with inputs 40 then 12.
| Working | Reason |
|---|---|
| a = 40 and b = 12; SUB a gives 12 − 40, which is negative | The negative flag is set |
| BRP is not taken, so the program falls through | BRP branches only on zero or positive |
| LDA a then OUT outputs 40 | The first number is the larger |
| HLT stops after 9 instructions, the same as before | Both paths are the same length |
With equal inputs, such as 25 and 25, the subtraction gives 0, BRP jumps, and the program outputs b, which is 25. The result is correct either way.
A program with several conditions, such as grading a mark, becomes a chain of subtractions and branches, one for each boundary. Each branch either jumps to the code for one grade or falls through to the next test. The order of the tests matters here exactly as it does in an ELSEIF chain.
Assembly language shows that a high-level IF is not magic. The processor only ever subtracts, checks the result and decides whether to change the program counter. Every decision a program makes, however complex it looks, comes down to steps like these.
Tracing a branching program means following one path at a time. For each set of inputs, work out the result of the subtraction, decide whether the branch is taken, and continue from the right mailbox. Writing the path taken beside the trace makes it easy to check.
Check yourself. Which branch instruction would test whether two stored values are equal, and why?
Show the answer
BRZ. Subtracting one value from the other gives 0 exactly when they are equal, and BRZ branches only when the accumulator is 0.
Section 4
Iteration in assembly language
Loops from branches
A loop in assembly language is a branch that jumps backwards. A label marks the start of the loop. At the end of the body, a branch returns to that label. A test somewhere in the loop decides when to stop, by branching out or by not branching back.
Common mistake: forgetting a branch back to the start of the loop. Without a BRA or a conditional branch to the loop's label, the body runs once and the program falls through to whatever comes next. Every loop needs a jump backwards and a test that eventually ends it.
Count-controlled loops are made in the same way. A counter is stored in a mailbox, loaded, tested and changed on every pass. A FOR loop in a high-level language becomes exactly this pattern once it is compiled: set the counter, test it, run the body, change the counter and branch back.
Worked example 6: a countdown
This program outputs the input, then counts down to 0. Trace it with input 3.
INP
loop OUT
SUB one
BRP loop
HLT
one DAT 1
| Working | Reason |
|---|---|
| INP gives 3; OUT outputs 3; SUB one gives 2 | The first pass of the loop |
| BRP loop jumps back because 2 is positive | The loop repeats while the value is not negative |
| Outputs 2, 1 and 0 follow on later passes | Each pass subtracts the constant 1 |
| After 0, SUB gives −1, held as 999 with the negative flag set | BRP falls through, and HLT ends 14 instructions in all |
The countdown relies on BRP treating 0 as positive, so that 0 is output before the loop ends. If BRZ were used instead, the loop would behave quite differently. Choosing the right branch, and putting the test in the right place, decides exactly how many passes a loop makes.
Worked example 7: summing until zero
This program adds input numbers until a 0 is entered, then outputs the total. Trace it with inputs 12, 30, 7 and 0.
loop INP
BRZ done
ADD total
STA total
BRA loop
done LDA total
OUT
HLT
total DAT
| Working | Reason |
|---|---|
| 12 is not 0, so it is added to total, which becomes 12 | BRZ is not taken for a non-zero input |
| 30 and 7 are added in turn, giving 42 then 49 | BRA loop returns for the next input |
| The input 0 makes BRZ jump to done | 0 is the sentinel that ends the loop |
| LDA total then OUT outputs 49, after 20 instructions | 3 passes of 5, then 5 more |
A sentinel loop, like the summing program, reads values until a special value appears, here 0. The test for the sentinel must come straight after the input, before the value is used. Otherwise the sentinel itself would be added to the total, giving the wrong answer.
Worked example 8: multiplying by repeated addition
The LMC cannot multiply, so a program adds a to a running total b times. Trace it for a = 6 and b = 4.
| Working | Reason |
|---|---|
| Store a = 6, b = 4 and total = 0 | The total starts empty |
| Each pass: if b is 0, finish; else b = b − 1 and total = total + a | b counts the passes left |
| After 4 passes, total = 6 + 6 + 6 + 6 = 24 and b = 0 | The loop added 6 four times |
| BRZ jumps out, and 24 is output after 41 instructions | Every pass costs 8 instructions |
Derivation: how many instructions the multiplication takes
The program has a fixed start of 4 instructions, which read and store a and b. Each pass of the loop, for b greater than 0, runs 8 instructions: LDA b, BRZ, SUB one, STA b, LDA total, ADD a, STA total and BRA.
The final test is LDA b and BRZ, 2 instructions, and the finish is LDA total, OUT and HLT, 3 more. Adding them up gives a formula in b alone.
For b = 4 that is 41 instructions, and for b = 30 it is 249. The work grows with b, so putting the smaller number second makes the program faster.
Loops in assembly language show clearly why some algorithms are slow. Every pass costs a fixed number of instructions, so a loop that runs b times costs about b times that number. The derivation above is the same kind of counting used in Algorithm analysis and Big O notation, applied to real instructions.
Infinite loops are easy to write by accident. A loop whose test never becomes true, or that forgets to change its counter, runs until the machine is stopped. The LMC simulator in Figure 5.1 stops after a set number of instructions, which is a common way for tools to protect against this.
From loops to algorithms
With selection and iteration available, any algorithm can be written in the LMC, given enough mailboxes. Division can be done by repeated subtraction, counting how many times the divisor can be taken away before the result goes negative. Finding the largest of a list combines a loop with the comparison from section 3.
Programs grow long quickly, which is the main reason high-level languages were invented. But knowing how the loops and branches work underneath makes it much easier to understand what a compiler produces and why some loops are faster than others.
Check yourself. Using the countdown program, how many numbers are output for an input of 5, and what is the last one?
Show the answer
It outputs 5, 4, 3, 2, 1 and 0, which is six numbers, and the last is 0. After 0, the subtraction gives −1, so BRP does not branch back and the program halts.
Section 5
Addressing modes
What the operand means
An instruction's operand can be interpreted in different ways, called addressing modes. The mode decides where the processor finds the value to work on. The same instruction, LDA 20, can load four different values depending on the mode.
With immediate addressing, the operand is the value itself, so LDA #20 loads 20. With direct addressing, the operand is the address of the value, so LDA 20 loads whatever mailbox 20 holds. The LMC uses direct addressing for every instruction that has an address.
Common mistake: treating an immediate operand as an address. In immediate addressing, LDA #20 loads the number 20 itself, with no memory access at all. Reading memory location 20 instead is direct addressing, which gives whatever value happens to be stored there.
Immediate addressing is the fastest mode, because the value arrives with the instruction itself. It suits constants, such as adding 1 to a counter. The cost is that the value is fixed when the program is written, and it must fit in the operand field, so large values cannot be given this way.
Direct addressing reads one memory location, so the value can be changed while the program runs. All the LMC's addressed instructions use it, which is why every constant in an LMC program, such as one, must be stored with DAT and loaded from memory.
Indirect and indexed addressing
With indirect addressing, the operand is the address of a location that holds the address of the value. The processor reads memory twice: once to get the real address, and again to get the value. Indirect addressing is how a program follows a pointer.
With indexed addressing, the value's address is the operand plus the contents of the index register. Changing the index register moves the same instruction along memory, one location at a time. Indexed addressing is how a program works through an array.
Common mistake: treating an indirect operand as the value's address. Indirect addressing goes to the operand's address, reads another address stored there, and loads from that second address. Stopping after the first read gives the direct value, not the indirect one.
Figure 5.2 shows LDA 20 under each mode, with the same memory. Choose a mode, change the index register, and see which cell is read. Then switch on the wrong model, which treats indirect addressing as direct.
Addressing modes
- Value loaded
- 80
- Effective address
- 35
- Memory reads
- 2
Some processors offer further modes. Relative addressing gives an address as an offset from the program counter, so a branch can say "jump forward 5" rather than naming a fixed mailbox. Code written this way can be loaded anywhere in memory and still work, which helps operating systems place programs freely.
Worked example 9: four modes, one operand
Memory holds 35 at address 20, 80 at address 35, 9 at address 22, and the index register holds 2. Find the value LDA 20 loads under each mode.
| Working | Reason |
|---|---|
| Immediate: the operand is the value, so 20 | No memory is read |
| Direct: address 20 holds 35, so 35 | One memory read at the operand |
| Indirect: address 20 holds 35, and address 35 holds 80, so 80 | Two reads: the address, then the value |
| Indexed: 20 + 2 = 22, and address 22 holds 9, so 9 | The index register is added first |
Each extra memory read takes time, because memory is much slower than the processor's registers. So immediate addressing is the fastest, direct and indexed take one read, and indirect takes two. A processor chooses its modes so that common tasks need as few reads as possible.
The mode is part of the instruction. A real processor uses a few bits of each instruction to say which mode applies, so the same opcode, such as LDA, can appear with different modes. Assembly languages mark the modes with symbols, such as # for immediate.
Worked comparison of speed
Suppose each memory read takes 10 nanoseconds and a register access takes less than 1. Loading a constant immediately costs almost nothing beyond the instruction itself. Loading it directly costs one read, 10 nanoseconds, and following a pointer indirectly costs two, 20 nanoseconds. In a loop that runs a million times, those differences add up to whole milliseconds.
Addressing modes are not only for loading. The same modes apply to storing, adding and comparing. So an instruction such as ADD can add a constant, a variable, an array element or the value at the end of a pointer. Learning the four modes once covers every instruction that uses them.
Check yourself. With the same memory, how many memory reads does each of the four modes need to load its value?
Show the answer
Immediate needs no reads, because the value is in the instruction. Direct and indexed need one read each. Indirect needs two: one to find the address and one to fetch the value.
Section 6
Addressing modes in use
Arrays with indexed addressing
An array is stored in consecutive memory locations. With indexed addressing, the operand holds the base address of the array, and the index register holds the position of the element. Setting the index register to 0, 1, 2 and so on visits each element with the same instruction.
A loop that adds up an array first sets the index register to 0. Each pass loads the element, adds it to a total and adds 1 to the index register, until the end of the array. The loop body never changes; only the index register does. This is exactly how a compiler turns a FOR loop over an array into machine code.
Common mistake: forgetting to add the index register. In indexed addressing, the effective address is the operand plus the index register. Using the operand alone reads the first element of the array every time, so a loop over the array processes the same value again and again.
Worked example 10: walking an array
An array starts at address 20 and holds 35, 44, 9 and 61. A loop loads each element with indexed addressing and adds it to a total. Find the effective addresses and the total.
| Working | Reason |
|---|---|
| Index 0: address 20 + 0 = 20, value 35 | The first element is at the base address |
| Index 1 and 2: addresses 21 and 22, values 44 and 9 | Each pass adds 1 to the index register |
| Index 3: address 23, value 61 | The last of the four elements |
| Total = 35 + 44 + 9 + 61 = 149 | One instruction read all four elements |
Indexed addressing also handles arrays of records. If each record takes four memory locations, the index register is increased by 4 each pass, and a fixed offset in the operand picks out the field. The address of a field is then base + 4 × position + offset, which is the same calculation as the row-major addresses in Arrays, records, stacks and queues.
Pointers with indirect addressing
A pointer is a memory location that holds the address of something else. Indirect addressing follows it in one instruction. If the item the pointer refers to moves, only the pointer needs updating; every instruction that uses it indirectly still finds the item.
Linked lists rely on this. Each node holds a pointer to the next node, and following the list means loading each pointer and using it as an address. Operating systems use tables of pointers to find routines, so that code can be moved in memory without rewriting every instruction that calls it.
Indirect addressing also makes jump tables possible. A menu program can store the address of each option's code in a table, and use indirect addressing to jump to the chosen one. Adding an option means adding an entry to the table, without changing the jump instruction.
Worked example 11: following a pointer
Address 50 holds 70, which is a pointer. Address 70 holds 12. Find what LDA 50 loads with direct and with indirect addressing, and what changes if the item moves to address 85.
| Working | Reason |
|---|---|
| Direct: address 50 holds 70, so 70 is loaded | Direct reads the operand's location once |
| Indirect: 50 holds 70, and 70 holds 12, so 12 is loaded | Indirect follows the pointer |
| If the item moves to 85, set address 50 to hold 85 | Only the pointer is updated |
| LDA 50 in indirect mode still loads the item | The instruction itself never changes |
Choosing a mode
Each mode has its own job. Immediate suits constants. Direct suits a single variable stored at a known place. Indexed suits arrays, where one instruction must reach many neighbouring locations. Indirect suits pointers, where the location of the data is itself stored as data and may change.
A compiler chooses the mode for every instruction it produces. When it translates total = total + scores[i], it uses direct addressing for total and indexed addressing for scores[i], with i in the index register. The programmer never sees the choice, but it decides how fast the code runs.
Security also depends on addressing. A program that lets the index register run past the end of an array will read or overwrite whatever lies beyond it. Many attacks on real software have exploited exactly this kind of error, which is why high-level languages usually check array indices for you.
Check yourself. Which addressing mode suits a constant, such as adding 1 to a counter, and why?
Show the answer
Immediate addressing suits a constant. The value 1 is part of the instruction, so no memory location has to be set aside for it. No memory read is needed either, which also makes it fast.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Machine code | Binary instructions the processor runs | 306 | Specific to one processor family |
| Assembly language | Mnemonics for machine code | STA 6 | One line per instruction |
| Opcode and operand | The operation, then its data or address | 5 and 12 in 512 | opcode = code DIV 100 in the LMC |
| LDA and STA | Load into, and store from, the accumulator | LDA b, STA total | LDA reads memory; STA writes it |
| BRZ and BRP | Branch on zero, branch on zero or positive | BRP second | Used after SUB to compare values |
| BRA | Branch always | BRA loop | Makes the jump back in a loop |
| Immediate addressing | The operand is the value | LDA #20 loads 20 | No memory read |
| Direct addressing | The operand is the value's address | LDA 20 loads 35 | One memory read |
| Indirect addressing | The operand is the address of the address | LDA 20 loads 80 | Two memory reads; follows a pointer |
| Indexed addressing | Operand plus the index register | 20 + 2 = 22 | Walks through an array |
Programming task
Programming task: multiplication in the LMC
Aim
Write an LMC program that reads two numbers and outputs their product, using repeated addition. Test it with values that include zero and an answer too large for the LMC, and measure how the number of instructions depends on the inputs.
Design
The program stores the two inputs as a and b and keeps a running total, starting at 0. Each pass of the loop first checks whether b is 0; if it is, the loop ends. Otherwise it subtracts 1 from b and adds a to the total, then branches back.
A constant one, stored with DAT 1, is used to count b down. The test is at the top of the loop, so an input of b = 0 skips the loop completely and outputs 0, as it should.
Code
INP
STA a
INP
STA b
loop LDA b
BRZ done
SUB one
STA b
LDA total
ADD a
STA total
BRA loop
done LDA total
OUT
HLT
a DAT
b DAT
total DAT
one DAT 1
The loop has a test at the top, BRZ done, and a jump back at the bottom, BRA loop. Every value the loop needs is loaded from memory and stored back, because the accumulator can only hold one value at a time.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | 6 then 4 | 24, in 41 instructions | A normal case, matching worked example 8 |
| 2 | 4 then 6 | 24, in 57 instructions | Same product; a larger b takes longer |
| 3 | 7 then 0 | 0, in 9 instructions | b = 0 skips the loop entirely |
| 4 | 0 then 5 | 0, in 49 instructions | a = 0 still runs every pass |
| 5 | 3 then 7 | 21, in 65 instructions | Checks the formula 8b + 9 |
| 6 | 12 then 12 | 144, in 105 instructions | A larger product |
| 7 | 50 then 30 | 500, in 249 instructions | 1500 overflows and wraps round |
Evaluation
The program gives the right product for every test whose answer fits in three digits, and tests 3 and 4 show that zero is handled correctly. Tests 1 and 2 confirm the derivation: the time depends on b, so swapping the inputs to put the smaller one second would save instructions.
Test 7 shows the LMC's limit. The true product, 1,500, needs four digits, so the accumulator wraps round to 500 with no warning. An improvement would compare the inputs first and swap them so that b is the smaller, and check for overflow before outputting.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. State the difference between an opcode and an operand.
Worked solution to Q1
The opcode is the part of an instruction that says which operation to carry out, such as ADD. The operand is the part that gives the data, or the address of the data, that the operation works on.
Q2. Describe what the LMC instructions BRA, BRZ and BRP do.
Worked solution to Q2
BRA always jumps to the given mailbox. BRZ jumps only if the accumulator is zero. BRP jumps if the accumulator is zero or positive. If a conditional branch is not taken, the next instruction runs as normal.
Q3. State an advantage and a disadvantage of writing a program in assembly language.
Worked solution to Q3
An advantage is that the program can be very fast and small, with direct control of the hardware. A disadvantage is that it is slow to write and hard to read, and it only runs on one family of processor.
Rung 2: Application
Q4. Decode the LMC instructions 218, 604 and 901.
Worked solution to Q4
First, 218 has opcode 2, so it is SUB 18. Next, 604 has opcode 6, so it is BRA 4, which always jumps to mailbox 4. Finally, 901 is the input instruction, INP.
Q5. Trace the larger-number program with inputs 7 then 3, and give the output.
Worked solution to Q5
After storing a = 7 and b = 3, SUB a gives 3 − 7, which is negative. BRP is not taken, so the program loads a and outputs 7, which is the larger number.
Q6. Suppose address 20 holds 35 and address 35 holds 80. Find what LDA 20 loads with direct and with indirect addressing.
Worked solution to Q6
Direct addressing reads address 20 once, so it loads 35. Indirect addressing reads address 20 to get 35, then reads address 35, so it loads 80.
Q7. Trace the summing program with inputs 5, 8, 3 and 0, and give the output.
Worked solution to Q7
The inputs 5, 8 and 3 are not zero, so each is added in turn, giving totals of 5, 13 and 16. The input 0 makes BRZ jump to done, so the program outputs 16.
Rung 3: Analysis
Q8. Use the formula steps = 8b + 9 to find how many instructions the multiplication program runs for inputs 9 and 6.
Worked solution to Q8
Here b = 6, so the steps are 8 × 6 + 9 = 48 + 9 = 57 instructions. Entering the numbers the other way round, with b = 9, would take 8 × 9 + 9 = 81 instructions.
Q9. Explain why the larger-number program stores both inputs, rather than keeping them in the accumulator.
Worked solution to Q9
The accumulator holds only one value, and the second INP overwrites the first. Both numbers are needed later, to subtract and then to output the larger, so each must be saved in a mailbox with STA.
Q10. An array starts at address 40 and the index register holds 5. Find the effective address for indexed addressing with operand 40.
Worked solution to Q10
The effective address is the operand plus the index register, so it is 40 + 5 = 45. That is the sixth element of the array, because the first element has index 0.
Q11. Explain why a negative result in the LMC can be confusing when it is output.
Worked solution to Q11
The LMC stores only 000 to 999, so a negative result such as −20 is held as 980. BRP still treats it as negative, but OUT prints 980. A program must test the sign before outputting, or the output will look like a large positive number.
Rung 4: Stretch
Q12. Using the derivation, show that the multiplication program's running time grows linearly with b, and find b for exactly 169 instructions.
Worked solution to Q12
The steps are 8b + 9, a straight-line function of b, so the time grows linearly. Setting 8b + 9 = 169 gives 8b = 160, so b = 20.
Q13. Explain how indirect addressing lets a program use a data item after the item is moved in memory.
Worked solution to Q13
The instruction holds the address of a pointer, not of the item. When the item moves, only the pointer is changed to the new address. The instruction still reads the pointer and follows it, so it finds the item without being changed.
Q14. An array of 4 values starts at address 20 and holds 35, 44, 9 and 61. Find the mean of the values that a loop with indexed addressing would read.
Worked solution to Q14
The loop reads addresses 20 to 23 in turn, giving 35, 44, 9 and 61. Adding these gives a total of 149. Dividing by the 4 values gives a mean of 149 ÷ 4 = 37.25.
Exam practice
Exam technique and worked answer workshop
For an LMC trace, draw columns for every mailbox that changes, the accumulator and the output. Add a row for every instruction executed, including branches, and show where each branch goes. Examiners give marks for the values in the accumulator and mailboxes as well as for the final output.
When writing an LMC program, put HLT before the DAT lines, so data is never run as an instruction. Give every label a DAT line, and use DAT 1 for a constant. Check that every loop has a test that ends it and a branch back to its start.
For addressing modes, state how many memory reads each needs and where the value comes from. A diagram with arrows from address to address is often the quickest way to get indirect addressing right.
Exam question 1 (4 marks · Paper 01 · about 5 minutes)
(a) Explain the difference between machine code and assembly language. [2]
(b) State the purpose of an assembler. [1]
(c) Decode the LMC instruction 512. [1]
Mark scheme for exam question 1
- B1 machine code is the binary instructions the processor runs
- B1 assembly language uses mnemonics, one for each machine code instruction
- B1 an assembler translates assembly language into machine code
- B1 LDA 12
Exam question 2 (5 marks · Paper 01 · about 7 minutes)
An LMC program is INP, STA first, INP, ADD first, OUT, HLT, first DAT.
(a) State the machine code stored in mailboxes 1 and 3. [2]
(b) Trace the program with inputs 25 and 17, giving the accumulator after each instruction and the output. [3]
Mark scheme for exam question 2
- B1 mailbox 1 holds 306
- B1 mailbox 3 holds 106
- B1 accumulator 25 after the first INP and STA
- B1 17 after the second INP, then 42 after ADD
- B1 output 42
Exam question 3 (5 marks · Paper 01 · about 7 minutes)
The larger-number program from worked example 4 is run.
(a) Trace it with inputs 12 and 40, stating the result of SUB a and whether BRP branches. [3]
(b) State the output for inputs 40 and 12, and explain why. [2]
Mark scheme for exam question 3
- B1 a = 12 and b = 40 stored
- B1 SUB a gives 28
- B1 28 is positive so BRP branches to second, and 40 is output
- B1 40 is output
- B1 12 − 40 is negative, so BRP does not branch and a is loaded and output
Exam question 4 (5 marks · Paper 01 · about 7 minutes)
Memory holds 35 at address 20, 80 at address 35 and 9 at address 22. The index register holds 2. Give the value loaded by LDA 20 under each mode, and the number of memory reads for indirect addressing.
Mark scheme for exam question 4
- B1 immediate: 20
- B1 direct: 35
- B1 indirect: 80
- B1 indexed: 9
- B1 indirect needs two memory reads
Exam question 5 (6 marks · Paper 01 · about 9 minutes)
A company is writing software for a small battery-powered sensor with very little memory, and a desktop app that displays the sensor's readings. Discuss whether each should be written in assembly language or a high-level language.
Mark scheme for exam question 5
Level 3 (5–6 marks): a justified choice for both programs, weighing speed, size, hardware control, development time and portability. The answer reaches a clear conclusion for each. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): a correct choice for both programs with some justification, or a well-justified choice for one. The comparison is limited.
Level 1 (1–2 marks): some relevant points, such as that assembly language is fast, with little application. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- assembly language gives small, fast code with direct control of the hardware
- the sensor has little memory and a battery, so small, efficient code matters
- assembly can control the sensor's hardware and registers directly
- assembly is slow to write, hard to read and specific to one processor
- a high-level language is quicker to write, easier to maintain and portable
- the desktop app has plenty of memory, so the efficiency of assembly is not needed
- the app needs a user interface, which libraries for high-level languages provide
- conclusion: assembly, or C with some assembly, for the sensor; a high-level language for the app
Annotated model answer: exam question 5
"The sensor has very little memory and runs on a battery. Assembly language produces small, fast code, with nothing added that the programmer did not write, and it can control the sensor's hardware registers directly." (Assembly, applied to the sensor.)
"Assembly is slow to write and hard to maintain, and it only runs on that one processor. For the sensor these costs are worth paying, because the program is small and the hardware will not change." (Drawbacks weighed for the sensor.)
"The desktop app runs on a computer with plenty of memory, so the efficiency of assembly gives no real benefit. A high-level language is quicker to write and easier to maintain, and its libraries provide the windows and charts the app needs." (High-level language, applied to the app.)
"So the sensor should be written in assembly language, or mostly in a low-level language, and the app in a high-level language." (A justified conclusion for both.)
This answer reaches Level 3 and scores 6 marks. It weighs both languages against each program's needs and reaches a clear choice for each.
Exam question 6 (6 marks · Paper 02 · about 9 minutes)
Write an LMC program that reads numbers until a 0 is entered, then outputs their total.
Mark scheme for exam question 6
- B1 INP inside a labelled loop
- B1 BRZ to leave the loop when the input is 0
- B1 ADD total then STA total to keep the running total
- B1 BRA back to the start of the loop
- M1 after the loop, LDA total then OUT
- A1 HLT, with total declared by DAT
Annotated model answer: exam question 6
loop INP
BRZ done
ADD total
STA total
BRA loop
done LDA total
OUT
HLT
total DAT
The labelled INP earns the first mark, and BRZ done the second, because 0 is the sentinel. ADD total and STA total keep the running total, and BRA loop returns for the next input. Loading and outputting the total earns the method mark, and HLT with the DAT earns the last.
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
(a) Explain how indexed addressing is used to process an array. [2]
(b) An array starts at address 20 and the index register holds 3. State the effective address. [1]
(c) State why the same instruction can read every element. [1]
Mark scheme for exam question 7
- B1 the operand holds the base address of the array
- B1 the index register holds the position, and is added to the operand
- B1 23
- B1 only the index register changes between passes, not the instruction
Exam question 8 (5 marks · Paper 01 · about 7 minutes)
The multiplication program from the programming task is run.
(a) State the output for inputs 6 and 4. [1]
(b) Calculate the number of instructions executed for inputs 6 and 4, using steps = 8b + 9. [2]
(c) Explain why entering 4 then 6 gives the same output but takes longer. [2]
Mark scheme for exam question 8
- B1 24
- M1 8 × 4 + 9
- A1 41 instructions
- B1 b is now 6, so the loop runs 6 times instead of 4
- B1 each pass costs 8 instructions, giving 57 in total
Connections
Synoptic link
The LMC is a model of the processor in Processor architecture and performance. Its program counter and accumulator are real registers, and every LMC step is one fetch-decode-execute cycle, using the memory address register and memory data register behind the scenes.
Assembly language is the lowest-level language in Translators and programming paradigms, which explains how compilers produce it from high-level code. Indexed addressing is how the arrays in Arrays, records, stacks and queues are reached, and indirect addressing follows the pointers in Linked lists, hash tables, graphs and trees.
Synoptic question 1. A processor runs at 2 GHz and each LMC-style instruction takes one clock cycle. Estimate how long the multiplication program takes for b = 30.
Answer to synoptic question 1
The program runs 8 × 30 + 9 = 249 instructions. At 2 × 10⁹ cycles a second, that takes 249 ÷ (2 × 10⁹) seconds, which is about 1.2 × 10⁻⁷ seconds, or 125 nanoseconds.
Recap
Recap and next step
- Machine code is binary instructions; assembly language writes each as a mnemonic, and an assembler translates it line for line.
- An LMC instruction is an opcode and a two-digit address: LDA loads, STA stores, ADD and SUB do arithmetic, and INP, OUT and HLT handle input, output and stopping.
- Selection is a subtraction followed by BRZ or BRP; the branch skips to a label, or falls through to the next instruction.
- A loop is a labelled block with a jump backwards and a test that ends it; repeated addition multiplies in 8b + 9 instructions.
- Immediate addressing holds the value, direct holds its address, indirect holds the address of the address, and indexed adds the index register.
- Indexed addressing walks through arrays, and indirect addressing follows pointers, so items can move without changing instructions.
Next chapter: Software development methodologies looks at how teams plan, build and test whole programs, from the waterfall model to agile methods.
For your exam board
OCR A Level Computer Science (H446): this chapter covers low-level languages, the Little Man Computer instruction set, and immediate, direct, indirect and indexed addressing in section 1.2.4, Types of programming language, in Component 01, Computer systems.
AQA A Level Computer Science (7517): machine code and assembly language, the relationship between them, instruction formats with opcodes and operands, and immediate and direct addressing appear in the fundamentals of computer organisation and architecture section, assessed on Paper 2.