SQ in silver chrome letters, a lab's gear stacked against the S: a rack, two oscilloscopes, pizza boxes and a six-pack. Strange Query Lab

CARDIAC › Tips and tricks › Comparisons

Test for zero with SUB 00

Say you want to print 42 n times, where n comes on a card and can be 0.

The loop has to stop when n reaches 0, and "is it 0?" sounds like an equality test, which on CARDIAC is two questions. A count is never negative, so the question left is "is n above 0?", and the way to ask that is to subtract n from 0. That needs a cell holding 0, and n still has to be counted down on its own afterwards.

cell  contents  notes
 10      030    INP 30  cells 10-14: is n above 0? 0 - n is negative when it is
 11      131    CLA 31
 12      730    SUB 30
 13      315    TAC 15
 14      820    JMP 20
 15      532    OUT 32  cells 15-20: the body, then count n down and test again
 16      130    CLA 30
 17      700    SUB 00
 18      630    STO 30
 19      811    JMP 11
 20      900    HRS 00
 30      000    n
 31      000    0
 32      042    what the body prints

Step through the natural way in Cardigan

Here's the trick: when x can't be negative, x is 0 exactly when x - 1 is negative. The 1 comes free from cell 00. Better still, when the answer is no, x - 1 is already sitting in the accumulator, and it's the count you were about to store. The test and the counting down are the same subtraction.

cell  contents  notes
 10      030    INP 30  cells 10-13: n - 1 is negative only when n is 0, and otherwise it is the new count
 11      130    CLA 30
 12      700    SUB 00
 13      317    TAC 17
 14      630    STO 30  cells 14-17: keep the new count, the body, and test again
 15      532    OUT 32
 16      811    JMP 11
 17      900    HRS 00
 30      000    n
 32      042    what the body prints

Step through the CARDIAC way in Cardigan

Both print 42 three times. Subtracting from 0 takes 14 cells and runs 30 instructions; SUB 00 takes 10 cells and runs 23.

Later processors merged the same two jobs into one instruction. The Z80's DJNZ takes one from register B and jumps unless it has reached zero, and x86's LOOP does the same with the CX register, so counting down and testing for zero are a single step.

From the tips in cardiac-code on GitHub. All the tips.