19. Stack Operations: Last In, First Out
Save values on the data stack and restore them in reverse order.
Open this lesson →
1. Predict and trace
Before running the Try program, predict its output and trace the first three executed instructions. Track the relevant registers, flags or memory as needed. Then step the program to compare.
LOAD 11
PUSH
LOAD 22
PUSH
POP
PRINT
POP
PRINT
HALT
Queue input: None
Initialize memory: All bytes initially zero
2. Build and check
Read two integers, save both on the data stack, then print them in reverse order. Use PUSH and POP rather than hardcoded values.
Required instruction types: INPUT, PUSH, POP
Starter program
INPUT
PUSH
INPUT
PUSH
# Pop and print twice.
HALT
Your program and notes
3. Explain the machine
Why does the second supplied value print first?
20. Calling a Subroutine
Reuse code and return to the instruction after CALL.
Open this lesson →
1. Predict and trace
Before running the Try program, predict its output and trace the first three executed instructions. Track the relevant registers, flags or memory as needed. Then step the program to compare.
LOAD 3
CALL square
PRINT
LOAD 4
CALL square
PRINT
HALT
square: MUL R0
RETURN
Queue input: None
Initialize memory: All bytes initially zero
2. Build and check
Read two integers. Call the same square subroutine for each and print the two squares in input order.
Required instruction types: INPUT, CALL, MUL, RETURN
Starter program
INPUT
CALL square
PRINT
INPUT
CALL square
PRINT
HALT
square:
# R0 in, R0 squared out.
RETURN
Your program and notes
3. Explain the machine
Why do two calls to the same code return to different places?
21. Preserving a Caller’s State
Use a save/restore convention when a function needs scratch space.
Open this lesson →
1. Predict and trace
Before running the Try program, predict its output and trace the first three executed instructions. Track the relevant registers, flags or memory as needed. Then step the program to compare.
LOAD 1 R1
LOOP 3
LOAD R1
CALL double
PRINT
LOAD R1
ADD 1
COPY R0 R1
RETURN
HALT
double: MUL 2
RETURN
Queue input: None
Initialize memory: All bytes initially zero
2. Build and check
Read a saved value into R1, then a function argument. Call a helper that returns argument + 1 while temporarily using R1 as scratch space. Print the result and then the preserved first value. Use PUSH and POP to preserve R1.
Required instruction types: INPUT, PUSH, POP, CALL, RETURN
Starter program
INPUT
COPY R0 R1
INPUT
CALL helper
PRINT
LOAD R1
PRINT
HALT
helper:
# Preserve R1, calculate argument + 1, restore R1.
RETURN
Your program and notes
3. Explain the machine
Which saved state belongs to the caller rather than the function result?