Lesson 4. Loops and conditions: multiplication by repeated addition
In picturesThere are no new parts in this lesson — only a program. The processor cannot multiply, but it can repeat: 13 × 11 is 13 added 11 times. A counter in memory, flag Z and a conditional jump — and the loop is ready.
4.1. The idea: a counter down to zero
- the sum lies in cell 0, the counter in cell 1;
- in the loop: sum + 13, counter − 1;
SUB #1sets flagZwhen the counter has reached zero;JNZ loopgoes back to the start of the loop whileZ= 0.
The card will receive a byte the same way: "take a bit 8 times".
4.2. The program
The same project as in lesson 3. No new parts: jumps on flags were built in lesson 2, the memory in lesson 3. This lesson is about how programs are written on them.
| Command | Jumps if | Flag is set by |
|---|---|---|
| JMP | always | — |
| JZ | Z = 1 (the result was 0) | LD, ADD, ADC, SUB, AND, OR, XOR, CMP |
| JNZ | Z = 0 | the same |
| JC | C = 1 (carry; for SUB/CMP — A ≥ B) | ADD, ADC, SUB, CMP |
| JNC | C = 0 | the same |
| CALL | always, remembering the return address | — |
| RET | to the remembered address | — |
Step 1. The program in the ROM
⚙ on ROM → button ⬆ → file 04-mul.rom.json. Clock can be set to 10Hz — the loop is long.
; Lesson 4 — multiplication by repeated addition: 13 × 11 = 143. The counter in cell 1 goes down to zero — a loop, like the card's; "receive 8 bits". JNZ looks at flag Z, which SUB has set. LD #0 ST 0 ; sum = 0 LD #11 ST 1 ; counter = 11loop: LD 0 ADD #13 ST 0 ; sum = sum + 13 LD 1 SUB #1 ST 1 ; counter = counter − 1 JNZ loop ; not zero — once more LD 0 ; the answer is in A, on the lampsdone: JMP done ; stop: the program steps in place4.3. Checking
Reset (RST for one or two clocks) — and watch the loop go. One row is one pass (7 commands from loop to JNZ):
| Pass | Clock | Counter (cell 1) | Sum (cell 0) | Z | JNZ |
|---|---|---|---|---|---|
| 1 | 11 | 10 | 13 | 0 | once more |
| 2 | 18 | 9 | 26 | 0 | once more |
| 3 | 25 | 8 | 39 | 0 | once more |
| 4 | 32 | 7 | 52 | 0 | once more |
| 5 | 39 | 6 | 65 | 0 | once more |
| 6 | 46 | 5 | 78 | 0 | once more |
| 7 | 53 | 4 | 91 | 0 | once more |
| 8 | 60 | 3 | 104 | 0 | once more |
| 9 | 67 | 2 | 117 | 0 | once more |
| 10 | 74 | 1 | 130 | 0 | once more |
| 11 | 81 | 0 | 143 | 1 | out of the loop |
| — | 83 | 0 | 143 | 0 | A = 143: stop, PC stands at 12 |
- Display
PCruns round 4 … 10, after the 11th pass it goes to 11, then stands at 12:JMP donejumps to itself. - At the end display
Aand the lamps show 143 (1000 1111). - Inside the loop
Ajumps between the sum and the counter: it is loaded now from cell 0, now from cell 1 — that is how it should be.
Think. What happens if the counter is set to 0? (The loop runs 256 times: 0 − 1 = 255, and zero is still far away.)
¿No te sale? Algo no funciona →