Lesson 4. Loops and conditions: multiplication by repeated addition

In pictures

There 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 #1 sets flag Z when the counter has reached zero;
  • JNZ loop goes back to the start of the loop while Z = 0.

The card will receive a byte the same way: "take a bit 8 times".

sum = 0, counter = 11sum = sum + 13counter = counter − 1zero?no (JNZ)yesA = 14313 × 11
No multiplier is needed — repetition is enough. The Z flag after SUB #1 says "the counter reached zero", JNZ decides: again or on.

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.

CommandJumps ifFlag is set by
JMPalways—
JZZ = 1 (the result was 0)LD, ADD, ADC, SUB, AND, OR, XOR, CMP
JNZZ = 0the same
JCC = 1 (carry; for SUB/CMP — A ≥ B)ADD, ADC, SUB, CMP
JNCC = 0the same
CALLalways, remembering the return address—
RETto 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 place

4.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):

PassClockCounter (cell 1)Sum (cell 0)ZJNZ
11110130once more
2189260once more
3258390once more
4327520once more
5396650once more
6465780once more
7534910once more
86031040once more
96721170once more
107411300once more
118101431out of the loop
—8301430A = 143: stop, PC stands at 12
  • Display PC runs round 4 … 10, after the 11th pass it goes to 11, then stands at 12: JMP done jumps to itself.
  • At the end display A and the lamps show 143 (1000 1111).
  • Inside the loop A jumps 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.)

Stuck? Something doesn't work →