Teacher answer key

The Stack and Functions

Gather four kinds of evidence: prediction of relevant state; behavior across varied cases including boundaries; explanation using trace/state evidence; and a reasoned correction of one mismatch. Mark each as emerging, with support or independent using paper or your school’s existing approved process. A challenge pass is machine-behavior evidence, not proof of authorship or complete mastery. Accept equivalent correct programs; the public key is a model, not the only possible answer.

Public teaching material. Solutions are examples; equivalent correct programs may also pass the actual checks.

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

Try prediction key

Output: 22, 11

InstructionPC beforePC afterR0 beforeR0 afterRelevant stateOutput
LOAD01011{"registers":[11,0,0,0,0,0,0,0],"flags":{"zero":false,"negative":false,"overflow":false},"sp":255,"stack":[],"callStack":[],"loopStack":[],"memoryReads":[],"memoryWrites":[]}None
PUSH121111{"registers":[11,0,0,0,0,0,0,0],"flags":{"zero":false,"negative":false,"overflow":false},"sp":254,"stack":[11],"callStack":[],"loopStack":[],"memoryReads":[],"memoryWrites":[]}None
LOAD231122{"registers":[22,0,0,0,0,0,0,0],"flags":{"zero":false,"negative":false,"overflow":false},"sp":254,"stack":[11],"callStack":[],"loopStack":[],"memoryReads":[],"memoryWrites":[]}None

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

Example challenge solution

INPUT
PUSH
INPUT
PUSH
POP
PRINT
POP
PRINT
HALT

Actual checker fixtures

Case 1
Input
3, 8
Initial memory
All bytes initially zero
Expected output
8, 3
Case 2
Input
-4, 0
Initial memory
All bytes initially zero
Expected output
0, -4
Case 3
Input
9, 9
Initial memory
All bytes initially zero
Expected output
9, 9

3. Explain the machine

Why does the second supplied value print first?

Reasoning and teaching note

PUSH/POP are LIFO; with inputs3,8 output 8,3; call frames are not data values.