Part 14 · Electronics and Computing
Programming
How to make a computer do useful work — algorithms, machine code and assembly language, a simple high-level language, the basic ways of arranging data, and how to write and test programs so they are right. And how to keep programs and knowledge safe in digital form for generations.
- Difficulty
- ●●●●●
- Time
- A few weeks to write simple programs; a lifetime to master. An afternoon for each example in this chapter
- Steps from zero
- 52 prerequisites →
You need first
The ComputerThe full path from nothing — 52 steps before this one
- Fire
- Cordage and Rope
- Stone Tools
- Finding and Preparing Clay
- Finding and Identifying Ores
- Sulfur
- Writing and Numbers
- Hunting and Trapping
- Basic Woodworking
- The Kiln
- Pottery
- Charcoal
- Arithmetic and Fractions
- Hides and Leather
- Lime
- Bricks
- Salt
- Mercury
- Lye and Potash
- Fermentation
- The Wheel and Axle
- Logic and Binary
- Glass
- Firebrick and Refractories
- Bellows
- Saltpeter
- The Lathe
- Gears
- Copper Smelting
- Iron (the Bloomery)
- Lead
- Laboratory Glassware
- Sulfuric Acid
- Pumps
- The Waterwheel
- Lenses
- Blacksmithing
- Gold and Silver
- Hydrochloric Acid
- The Battery
- The Vacuum Pump
- Magnets
- The Light Bulb
- Copper Wire
- Photography
- The Generator
- The Vacuum Tube
- The Electric Arc Furnace
- Pure Silicon
- Semiconductors and the Transistor
- Integrated Circuits
- The Computer
- Programming
Do them roughly in this order. See it on the tech tree →
Why it matters
A The Computer without a program is a heap of switches. Everything it does — every table it calculates, every letter it prints, every message it passes along a network — is a program someone wrote. Programming is the skill of breaking a job into steps so small and exact that a machine can follow them without understanding anything.
Programming needs no factory. It needs a clear head, pencil and Paper, and patience. A good program, once written and tested, can be copied for nothing and used for ever, and it does not wear out. That is also its danger: knowledge stored only as patterns of magnetism or charge can vanish in a few years. The last part of this chapter is about keeping it.
How it works
Algorithms
An algorithm is a recipe: a list of exact steps that, followed one at a time, always finish and always give the right answer. A good algorithm says what it starts with (the input), what it produces (the output), and never leaves a step open to guesswork.
The oldest algorithm still in daily use is Euclid's, written down about 300 BC, for the greatest common divisor: the largest number that divides two numbers exactly (useful for simplifying fractions and gear ratios, see Gears and Arithmetic and Fractions). In words: while the two numbers are different, replace the larger with the larger minus the smaller; when they are equal, that is the answer.
Before you write any program, write the algorithm in plain words or as a flowchart, and trace it by hand with a small example, writing the value of every variable after every step, as in the table in the figure. If you cannot do it by hand, the machine cannot either.
Machine code
The computer in The Computer understands only numbers. Each instruction is two numbers: a code (1 = LOAD, 2 = STORE, 3 = ADD, 4 = SUB, 5 = LOADI, 6 = JUMP, 7 = JZ, 8 = JNEG, 9 = IN, 10 = OUT, 11 = LOADP, 12 = STOREP, 0 = HALT) and an address or number. This program reads two numbers and prints their sum:
| Address | Numbers | Meaning |
|---|---|---|
| 0 | 9 0 | IN: A ← first input |
| 2 | 2 12 | STORE 12: keep it in cell 12 |
| 4 | 9 0 | IN: A ← second input |
| 6 | 3 12 | ADD 12: A ← A + cell 12 |
| 8 | 10 0 | OUT: show A |
| 10 | 0 0 | HALT |
| 12 | 0 | (the stored first number goes here) |
Typed into memory as 9 0 2 12 9 0 3 12 10 0 0 0 0 and run with inputs 7 and 5, it shows 12. This is machine code. It works, but it is miserable to write: change one instruction near the start and every address after it moves.
Assembly language
Assembly language is machine code written with names: names for the instructions, and labels for addresses. The same program:
IN
STORE X
IN
ADD X
OUT
HALT
X: 0
A label (like X:) names the address where it stands. Translating assembly to numbers is called assembling, and it is purely mechanical, done in two passes:
- First pass: go down the program counting addresses (2 for each instruction, 1 for each number) and write down the address of every label. Here X is 12.
- Second pass: replace each name with its code and each label with its address.
Do it by hand for your first programs. Then write an assembler — a program that does it — in machine code, once, carefully. After that you never assemble by hand again.
A loop — doing something again and again — is made with jumps. This program multiplies two numbers by repeated addition. Text after a semicolon is a comment, a note for people that the assembler ignores:
IN ; first number
STORE NUM
IN ; second number: how many times
STORE COUNT
LOADI 0
STORE PROD ; product starts at 0
LOOP: LOAD COUNT
JZ DONE ; nothing left to add: finished
SUB ONE
STORE COUNT ; count = count - 1
LOAD PROD
ADD NUM
STORE PROD ; prod = prod + num
JUMP LOOP
DONE: LOAD PROD
OUT
HALT
ONE: 1
NUM: 0
COUNT: 0
PROD: 0
And here is Euclid's algorithm, exactly as in the flowchart. JNEG makes the decision: after SUB Y, A is negative if Y was bigger than X.
IN
STORE X
IN
STORE Y
LOOP: LOAD X
SUB Y
JZ DONE ; x = y: finished
JNEG YBIG ; x - y is negative, so y is bigger
STORE X ; x = x - y
JUMP LOOP
YBIG: LOAD Y
SUB X
STORE Y ; y = y - x
JUMP LOOP
DONE: LOAD X
OUT
HALT
X: 0
Y: 0
Inputs 12 and 18 give 6; 35 and 21 give 7. (With 8-bit cells, keep the inputs below 128, or the "negative" test is fooled.)
Data structures
How you arrange data in memory matters as much as the steps you take.
- Numbers are single cells. For bigger numbers, use two or more cells together and carry from one to the next, as in long addition by hand.
- Text is a row of character codes (in the common ASCII code, "A" = 65, "a" = 97, "0" = 48, space = 32), ending with a 0.
- An array is a row of cells. Item i is at the start address plus i. To walk along one, keep the address of the current item in a cell — a pointer — and use LOADP. This program adds up a list that ends with 0:
LOADI 0
STORE SUM
LOADI LIST ; the ADDRESS of the list, not its contents
STORE PTR
LOOP: LOADP PTR ; A = the item PTR points at
JZ DONE ; a 0 marks the end of the list
ADD SUM
STORE SUM
LOAD PTR
ADD ONE
STORE PTR ; point at the next item
JUMP LOOP
DONE: LOAD SUM
OUT
HALT
ONE: 1
SUM: 0
PTR: 0
LIST: 5, 9, 2, 7, 0
- A record is a group of cells that belong together: a person's name, date of birth and village.
- A stack is an array used from one end only, with a pointer to the top: "push" puts an item on, "pop" takes the last one off. Stacks remember where to come back to after a subroutine (a piece of program used from many places).
- A queue is first in, first out: messages waiting to be sent.
- A linked list stores, with each item, the address of the next. Items can be inserted or removed by changing one address.
- A table (index, dictionary) finds an item by a key — a name, a number — using sorting and searching, below.
A simple language
Assembly is still slow to write. A high-level language lets you write what you mean, and a program called a compiler translates it into machine code (or an interpreter carries it out directly, more slowly). Here is a small language, enough for almost any job. Indentation shows which lines belong inside a while, if or function:
# add up 1 + 2 + ... + n
let n = input()
let total = 0
while n > 0:
total = total + n
n = n - 1
print(total)
| Written | Meaning |
|---|---|
let x = 5 |
Make a new variable called x, holding 5 |
x = x + 1 |
Change x. Also -, *, / (whole-number division) and % (remainder) |
== != < > <= >= |
Equal, not equal, less, more, and so on; join with and, or, not |
if ...: / else: |
Do the indented lines only if the test is true; otherwise the else lines |
while ...: |
Repeat the indented lines as long as the test is true |
for x in list: |
Repeat once for each item in a list |
[3, 1, 2], list[i], len(list) |
A list; its item number i (counting from 0); how many items it has |
function name(a, b): / return x |
A named piece of program that takes inputs and gives back an answer |
print(x), input() |
Output and input |
# ... |
A comment for people |
Euclid's method, written as a function so it can be used anywhere:
function gcd(x, y):
while x != y:
if x > y:
x = x - y
else:
y = y - x
return x
print(gcd(12, 18)) # prints 6
How a compiler translates it. Each kind of line becomes a fixed pattern of instructions. total = total + n becomes LOAD TOTAL, ADD N, STORE TOTAL. A while n > 0: loop becomes:
TOP: LOAD N
JZ END ; n = 0: leave the loop
JNEG END ; n < 0: leave the loop
... ; the indented lines
JUMP TOP
END:
Bootstrapping. Write the first, simplest compiler in assembly. Then write a better compiler in the language itself, compile it with the first one, and from then on improve the language using the language. Every programming system in history was lifted up this way, step by step from switches.
Sorting and searching
Two jobs come up constantly. Sorting puts a list in order; searching finds an item. Insertion sort is how people sort a hand of cards: take each item in turn and slide it left until it is in place.
function sort(list):
let i = 1
while i < len(list):
let item = list[i]
let j = i - 1
while j >= 0 and list[j] > item:
list[j + 1] = list[j] # move bigger items one place right
j = j - 1
list[j + 1] = item
i = i + 1
Once a list is sorted, binary search finds anything in it by halving, as you find a word in a dictionary. A list of 1,000 items takes at most 10 looks; a million, 20.
function find(list, wanted): # list must be sorted
let low = 0
let high = len(list) - 1
while low <= high:
let middle = (low + high) / 2
if list[middle] == wanted:
return middle
if list[middle] < wanted:
low = middle + 1
else:
high = middle - 1
return -1 # not in the list
Choosing a good algorithm matters more than a fast machine: insertion sort on 10,000 items makes about 25 million comparisons on average; better methods (merge sort, which splits the list in halves, sorts each half and merges them) need about 130,000.
What you need
- A working The Computer, or at first just pencil and paper: you can learn all of this by "being the computer" and tracing programs by hand.
- A way to put programs in and keep them: front-panel switches at first, then punched paper tape or cards (Punched-Card Tabulating Machines), then magnetic storage (Displays, Printers and Data Storage).
- A printer, The Teleprinter or typewriter output (The Typewriter) so programs and results can be read and kept on paper.
- A logbook: every program, every change, every bug found and how, with the date.
Step by step: writing a program that works
- Understand the job. Write down what goes in, what must come out, and an example worked by hand.
- Write the algorithm in words or as a flowchart. Trace it on your example.
- Choose the data structures. Where does each thing live? Draw the memory.
- Write the program in small pieces — functions or subroutines of 10–30 lines that each do one clear thing. Give variables names that say what they hold (
count, notc). Put a comment on anything that is not obvious. - Check it at the desk. Trace it with a table of variables, exactly as the machine would. Most bugs are found here, before the machine is even switched on.
- Test it on the machine with a planned list of test cases and the answers worked out in advance:
- an ordinary case,
- the edge cases: zero, one, the largest allowed number, an empty list, a list of one item, two equal items,
- wrong input: what should happen if someone types a letter where a number belongs?
- Debug when a test fails:
- Single-step the machine, or add
printlines, and find the first place where a value differs from your hand trace. - Halve the search: check the middle of the program; the bug is in the half where things first go wrong.
- Explain the program, line by line, to someone else (or to an empty chair). You will often hear the mistake yourself.
- Change one thing at a time, and run all the tests again after every change.
- Single-step the machine, or add
- Keep it: number every version, keep the old ones, and write in the log what changed and why.
Tip A program is not finished when it works. It is finished when someone else can read it, and when it has passed tests chosen to break it.
How to tell it worked
- Every planned test gives the answer worked out in advance.
- Edge cases (zero, empty, largest) behave sensibly.
- Someone else, reading only your comments and the logbook, can explain what the program does.
- The same program, given the same input a hundred times, gives the same answer every time.
Note Common bugs. Off by one → a loop runs one time too many or too few. Check the first and last pass by hand. Uninitialised variable → a cell used before anything was put in it, so it holds whatever was there before. Set every variable before use. Overflow → a number bigger than the cell can hold wraps round (255 + 1 = 0 in 8 bits). Check the largest values your program can meet. Wrong jump → a JZ or JNEG testing a value left over from a different instruction. Load the value you mean to test right before the jump. Infinite loop → the loop's test never becomes false. Make sure something in the loop moves towards the end every time round. Pointer errors → writing through a pointer that points to the wrong place silently destroys other data or the program itself.
Dangers
Danger Programs that control machines can kill. A computer that runs a boiler (The Steam Engine), a furnace, a railway signal or a medical device will one day meet a situation its programmer never imagined. In the 1980s a radiation-therapy machine (Radiotherapy (Overview)) whose safety depended on its software gave massive overdoses that killed or injured several patients. Always keep mechanical and electrical safety devices that do not depend on the program: pressure relief valves, limit switches, fuses, an emergency stop that cuts power directly.
- Loss of work. One power cut, one scratched tape, one mistaken command can erase months. Follow the rules below from the first day.
- Trusting output blindly. Check important results with a second method — by hand, or by a different program written by someone else.
Preserving software and knowledge digitally
Digital copies are perfect, cheap and compact: a single tape can hold more text than a library room. But they are fragile in time. The medium decays, the machine that reads it breaks and is not made any more, and the knowledge of how the data was arranged is forgotten. Nobody can read a perfectly preserved tape if no machine can play it and no one knows its format.
Follow these rules:
Three copies, two kinds of media, one far away. Never trust a single copy. Keep at least three, on at least two different kinds of storage, with one in a different building or town (see Libraries and Preserving Knowledge).
Check every copy with a checksum. A checksum is a number computed from all the data; if any bit changes, the checksum almost always changes too. A simple, good one:
function checksum(data): let a = 0 let b = 0 for byte in data: a = (a + byte) % 255 b = (b + a) % 255 return b * 256 + aBecause
badds up running totals, it also catches two bytes swapped. Store the checksum with the data, and recompute it whenever you copy or read.Copy to fresh media on a schedule — every few years for magnetic media — and check the new copy before discarding anything. This is called migration.
Use simple, written-down formats. Plain text, one character per cell, in a character code whose table is printed in the archive. Numbers in a stated order and size. If a format is not described on paper, assume it will be unreadable in fifty years.
Keep the keys on paper. Print, on acid-free Paper with carbon Ink, and store with the archive:
- a full description of the machine: its instruction set, word size and how storage is laid out,
- the character code table,
- the descriptions of every file format,
- the source code (the human-readable program text) of the assembler, compiler and loader, and of every important program,
- test programs with their expected results.
Print machine code in rows of 16 numbers with a checksum at the end of each row, so that anyone retyping it can find their mistakes line by line.
Describe the machine well enough to imitate it. A program that pretends to be the old computer — an emulator — lets old software run on new machines. It can only be written if the old machine is fully described. The description is worth more than the machine.
The most important knowledge should not be digital only. Medicine, farming, the steps of this book: keep them printed, in many copies, in many places. Digital storage is for speed and searching; paper and stone are for the long run.
Going further
- Subroutines and a stack built into the machine (CALL and RETURN instructions), so programs can be built from parts.
- An operating system: a program that loads other programs, manages storage and runs the printer and keyboard.
- Editors for writing programs on a screen, and text processing for printing books and records.
- Numerical methods: tables of logarithms and trigonometry (Algebra, Geometry and Trigonometry), surveying and navigation calculations, engineering design.
- Sharing programs over Networks and the Internet, which is also the best way to keep many copies in many places.
How it was first done
In 1843 Ada Lovelace, translating a paper on Charles Babbage's Analytical Engine, added notes including a step-by-step method for the machine to calculate the Bernoulli numbers, often called the first published program. Konrad Zuse designed a high-level language, Plankalkül, in the 1940s, though it was not implemented until much later. On the first stored-program computers in 1948–49, programs were written directly in numbers; at Cambridge, David Wheeler devised the subroutine and an early assembler for EDSAC, and Maurice Wilkes, Wheeler and Stanley Gill published the first programming textbook in 1951.
Grace Hopper wrote one of the first compilers (A-0) in 1952, and her later work on English-like languages shaped COBOL (1959), for business records. John Backus's team at IBM delivered FORTRAN, for scientific calculation, in 1957; John McCarthy created LISP in 1958; BASIC, designed at Dartmouth College in 1964 for students, brought programming to millions; and C (1972) became the language in which most later systems were written. The word "bug" was engineers' slang long before 1947, when Hopper's colleagues taped a moth found in a relay of the Harvard Mark II into their logbook as the "first actual case of bug being found". The lesson of that logbook still stands: write everything down.
Source: content/entries/electronics/programming.md