13. Loops: Repeating Things
Pair LOOP with RETURN and treat zero repeats correctly.
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 8 LOOP 4 PRINT RETURN HALT
Queue input: None
Initialize memory: All bytes initially zero
Try prediction key
Output: 8, 8, 8, 8
| Instruction | PC before | PC after | R0 before | R0 after | Relevant state | Output |
|---|---|---|---|---|---|---|
| LOAD | 0 | 1 | 0 | 8 | {"registers":[8,0,0,0,0,0,0,0],"flags":{"zero":false,"negative":false,"overflow":false},"sp":255,"stack":[],"callStack":[],"loopStack":[],"memoryReads":[],"memoryWrites":[]} | None |
| LOOP | 1 | 2 | 8 | 8 | {"registers":[8,0,0,0,0,0,0,0],"flags":{"zero":false,"negative":false,"overflow":false},"sp":255,"stack":[],"callStack":[],"loopStack":[{"start":1,"end":3,"remaining":4,"callDepth":0}],"memoryReads":[],"memoryWrites":[]} | None |
| 2 | 3 | 8 | 8 | {"registers":[8,0,0,0,0,0,0,0],"flags":{"zero":false,"negative":false,"overflow":false},"sp":255,"stack":[],"callStack":[],"loopStack":[{"start":1,"end":3,"remaining":4,"callDepth":0}],"memoryReads":[],"memoryWrites":[]} | 8 |
2. Build and check
Read a repeat count from 0 through 5. Print 8 exactly that many times, then halt.
Required instruction types: INPUT, LOOP, PRINT, RETURN
Example challenge solution
INPUT COPY R0 R1 LOAD 8 LOOP R1 PRINT RETURN HALT
Actual checker fixtures
Case 1
- Input
0- Initial memory
All bytes initially zero- Expected output
None
Case 2
- Input
1- Initial memory
All bytes initially zero- Expected output
8
Case 3
- Input
4- Initial memory
All bytes initially zero- Expected output
8, 8, 8, 8
3. Explain the machine
How many times does LOOP 0 execute its body?
Reasoning and teaching note
Zero; it skips the paired body/RETURN. A negative count errors instead.