13. Loops: Repeating Things
Pair LOOP with RETURN and treat zero repeats correctly.
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 8
LOOP 4
PRINT
RETURN
HALT
Queue input: None
Initialize memory: All bytes initially zero
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
Starter program
INPUT
COPY R0 R1
LOAD 8
LOOP R1
# Repeated instruction
RETURN
HALT
Your program and notes
3. Explain the machine
How many times does LOOP 0 execute its body?
14. Building a Counter
Print 1 to 10 and generalize the count.
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 5
again: PRINT
SUB 1
JUMP_IF_ZERO done
JUMP again
done: HALT
Queue input: None
Initialize memory: All bytes initially zero
2. Build and check
Read N from 0 through 10 and print every integer from 1 through N in order. For N = 0, print nothing.
Required instruction types: INPUT, LOOP, ADD, PRINT
Starter program
INPUT
COPY R0 R2
LOAD 1 R1
LOOP R2
# Print and advance R1.
RETURN
HALT
Your program and notes
3. Explain the machine
How do counter value and number of repetitions differ?
15. Sum One to N
Keep an accumulator separate from the loop counter.
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
LOAD 0 R2
LOOP 4
LOAD R2
ADD R1
COPY R0 R2
LOAD R1
ADD 1
COPY R0 R1
RETURN
LOAD R2
PRINT
HALT
Queue input: None
Initialize memory: All bytes initially zero
2. Build and check
Read N from 0 through 10. Use a loop to print the sum 1 + 2 + … + N. Print 0 for N = 0.
Required instruction types: INPUT, LOOP, ADD
Starter program
INPUT
COPY R0 R3
LOAD 1 R1
LOAD 0 R2
LOOP R3
# Add counter to total, then increment counter.
RETURN
LOAD R2
PRINT
HALT
Your program and notes
3. Explain the machine
What does the total represent after k iterations?