CAIE 9618 · Paper 1 · Topic 1.4.1
Assembly Language
Programming
Loops · Conditional Branching · Subroutines · Stack Operations
CSZone
Cambridge International AS & A Level Computer Science 9618
Loops in Assembly
Counting Down with a Counter
CAIE assembly loops typically use a counter variable and a conditional jump. The standard pattern: load counter → decrement → compare → jump back if not zero.
LDM #5
STO count
LDM #0
STO result
loop:
LDD result
INC ACC
STO result
LDD count
DEC ACC
STO count
CMP #0
JPN loop
END
PATTERN BREAKDOWN
1. Initialise counter (5) and result (0)
2. Increment result
3. Decrement counter
4. CMP #0 — if count ≠ 0, jump back
5. Exit when count reaches 0
Final result = 5
Subroutines & The Stack
Reusable Code Blocks
A subroutine is a named block of reusable code. CALL jumps to it, RET returns. The CPU uses the stack to remember where to return to.
CALL double
STO result
END
double:
LDD num
ADD num
RET
HOW THE STACK WORKS
CALL: pushes current PC (return address) onto stack. Jumps to subroutine.
RET: pops return address from stack. Loads it into PC. Execution resumes after CALL.
PUSH / POP
PUSH reg: saves register to top of stack
POP reg: retrieves from top of stack
Stack pointer (SP) tracks top of stack