You've seen transistors make gates, gates make adders, and gates make multiplexers and decoders. But a pile of adders isn't a computer. A computer must remember numbers between steps, follow a list of instructions in order, and jump back to repeat a loop. This lesson adds the two missing pieces, memory circuits and a clock, and puts everything together: you'll see how a CPU is built from logic gates, and run a tiny but complete CPU in Python that adds up 5 + 4 + 3 + 2 + 1 from a program stored as numbers in memory.
By the end, the ladder from the transistors lesson is complete: transistors, gates, adders and multiplexers, flip-flops and registers, the ALU and control unit, and finally a processor running a program.
What you need first: half adder and full adder and multiplexers and decoders.
Key terms
- Combinational circuit: output depends only on the current inputs (gates, adders, multiplexers). No memory.
- Sequential circuit: output depends on the inputs and what it stored before. It has memory.
- Latch / flip-flop: a circuit that stores one bit. A flip-flop only changes on a clock tick.
- Register: a row of flip-flops that stores one number, such as 64 bits.
- Clock: a signal that switches between 0 and 1 billions of times a second, telling every flip-flop when to update.
- ALU (arithmetic logic unit): the part of the CPU that calculates: add, subtract, AND, OR, compare.
- Control unit: the part that decodes each instruction and switches on the right parts of the CPU.
- Program counter (PC): a register holding the address of the next instruction.
Memory from gates: the latch
Every circuit so far forgets everything the moment its inputs change. To remember, a circuit needs a loop: an output fed back into an input.
Take two NOR gates and connect each one's output to the other's input. This is an SR latch (set–reset latch):
R ───> [NOR 1] ───┬───> Q
^ |
| v each gate's output is wired
| | into the other gate's input
^ v
S ───> [NOR 2] ───┴───> Q'
Gate 1 takes R and Q'; gate 2 takes S and Q.
It has two inputs, S (set) and R (reset), and an output Q:
| S | R | Q afterwards |
|---|---|---|
| 1 | 0 | 1 (set) |
| 0 | 1 | 0 (reset) |
| 0 | 0 | Stays as it was: this is the memory |
| 1 | 1 | Not allowed |
The interesting row is S = 0, R = 0: the loop keeps feeding Q back in, so Q holds whatever it was last set to. Simulating the two gates in Python:
def NOR(a, b):
return 1 - (a | b)
class SRLatch:
def __init__(self):
self.q, self.q_bar = 0, 1
def update(self, s, r):
for _ in range(3): # let the loop settle
self.q = NOR(r, self.q_bar)
self.q_bar = NOR(s, self.q)
return self.q
latch = SRLatch()
print("set: ", latch.update(s=1, r=0))
print("hold: ", latch.update(s=0, r=0))
print("reset:", latch.update(s=0, r=1))
print("hold: ", latch.update(s=0, r=0))
set: 1
hold: 1
reset: 0
hold: 0
After "set", Q stays 1 even when both inputs go back to 0. After "reset", it stays 0. Two gates, one remembered bit. This is how the CPU's own memory (registers and cache, built from SRAM) works; how RAM, hard disks and SSDs store data compares it with the main RAM chips.
The clock and the flip-flop
In a CPU, billions of circuits must change in step, or half-finished results would get stored. So the CPU has a clock: a signal that goes 0, 1, 0, 1 at a fixed rate. A D flip-flop is a latch with extra gates so that it copies its input D to its output Q only at the moment the clock goes from 0 to 1 (the "rising edge"), and ignores D the rest of the time.
The clock speed in GHz is how many of these ticks happen per second. At 3 GHz, a tick happens every third of a nanosecond, and in that time the signals must pass through all the gates between one set of flip-flops and the next. That's why the number of gates in a path (and the carry-lookahead trick from the adder lesson) matters for speed.
A register is just a row of D flip-flops sharing a clock: 8 of them hold a byte, 64 hold a 64-bit number. On each tick, the whole row loads a new value at once.
class Register:
def __init__(self, width=8):
self.bits = [0] * width
def tick(self, value): # rising clock edge: every flip-flop copies its input
self.bits = [(value >> i) & 1 for i in range(len(self.bits))]
def read(self):
return sum(bit << i for i, bit in enumerate(self.bits))
r = Register()
r.tick(77)
print(r.read(), r.bits)
77 [1, 0, 1, 1, 0, 0, 1, 0]
The bits are listed lowest first: 77 is 1 + 4 + 8 + 64.
The parts of a CPU
Now every part can be named, with what it's built from:
| Part | Job | Built from |
|---|---|---|
| Registers | Hold the numbers being worked on | Rows of flip-flops |
| Program counter (PC) | Holds the address of the next instruction | A register, plus an adder that adds 1 |
| Instruction register | Holds the instruction being carried out | A register |
| ALU | Adds, subtracts, ANDs, ORs, compares | Adders, gates, and a multiplexer that picks the result |
| Flags register | Records facts about the last result: zero, negative, carry, overflow | Flip-flops fed by gates |
| Control unit | Decodes the instruction and switches on the right paths | Decoders and gates |
| Multiplexers | Route the right register into the ALU, and the result back | MUXes |
| Buses | Bundles of wires connecting the CPU to memory | Wires, plus decoders to select addresses |
Instructions are stored in memory as numbers, just like data. The control unit's decoder looks at the first few bits of an instruction (the opcode) and switches on, say, "ALU: add" and "write result to register 2".
The fetch-decode-execute cycle
The CPU repeats three steps for ever:
- Fetch: read the instruction at the address in the PC into the instruction register, and add 1 to the PC.
- Decode: the control unit splits the instruction into its opcode and its operand (an address or register number), and sets up the multiplexers and ALU.
- Execute: the ALU calculates, and the result goes into a register or memory. A jump instruction instead writes a new address into the PC, which is how loops and
ifstatements work.
A tiny CPU in Python
Here's a complete, if very small, computer. It has 16 bytes of memory, one working register called the accumulator (ACC), and a PC. Each instruction is one byte: the top 4 bits are the opcode, the bottom 4 bits are an address.
| Opcode | Instruction | Does |
|---|---|---|
| 0 | HALT | Stop |
| 1 | LOAD a | ACC = memory[a] |
| 2 | ADD a | ACC = ACC + memory[a] |
| 3 | SUB a | ACC = ACC − memory[a] |
| 4 | STORE a | memory[a] = ACC |
| 5 | JZ a | If ACC is 0, jump to a |
| 6 | JMP a | Jump to a |
The program adds up n + (n − 1) + ... + 1, with n = 5 stored at address 13, the running total at 14, and the number 1 at 15:
HALT, LOAD, ADD, SUB, STORE, JZ, JMP = range(7)
def instr(op, addr=0):
return (op << 4) | addr # one byte: 4-bit opcode, 4-bit address
memory = [0] * 16
program = [
instr(LOAD, 13), # 0: ACC = n
instr(JZ, 8), # 1: if n == 0, go to the end
instr(ADD, 14), # 2: ACC = n + total
instr(STORE, 14), # 3: total = ACC
instr(LOAD, 13), # 4: ACC = n
instr(SUB, 15), # 5: ACC = n - 1
instr(STORE, 13), # 6: n = ACC
instr(JMP, 0), # 7: back to the start
instr(HALT), # 8: stop
]
memory[:len(program)] = program
memory[13], memory[14], memory[15] = 5, 0, 1
print("Program as numbers:", memory[:9])
pc, acc, steps = 0, 0, 0
while True:
instruction = memory[pc] # fetch
pc += 1
op, addr = instruction >> 4, instruction & 0b1111 # decode
steps += 1
if op == HALT: # execute
break
elif op == LOAD:
acc = memory[addr]
elif op == ADD:
acc = (acc + memory[addr]) & 0xFF
elif op == SUB:
acc = (acc - memory[addr]) & 0xFF
elif op == STORE:
memory[addr] = acc
elif op == JZ and acc == 0:
pc = addr
elif op == JMP:
pc = addr
print("Total:", memory[14], "after", steps, "instructions")
Program as numbers: [29, 88, 46, 78, 29, 63, 77, 96, 0]
Total: 15 after 43 instructions
Look at the first line: the program is just numbers in memory, 29, 88, 46..., sitting next to the data. 29 is 0001 1101: opcode 1 (LOAD), address 13. That's the stored-program idea that every computer since the late 1940s uses.
Map the Python back to hardware:
| In the simulation | In a real CPU |
|---|---|
memory list | RAM, with a decoder selecting the address |
pc, acc variables | Registers made of flip-flops |
instruction >> 4, & 0b1111 | Wires splitting the instruction register into opcode and address |
The if/elif chain | The control unit's decoder, enabling one path |
acc + memory[addr] | The ALU's adder |
& 0xFF | An 8-bit register simply has no ninth bit |
One pass of the while loop | One fetch-decode-execute cycle, a few clock ticks |
A real CPU has many more registers and hundreds of instructions, and runs several instructions at once (pipelining), but it's the same machine. The assembly language lesson shows real instructions written by hand.
How it all relates
From the bottom up:
- Transistors switch on and off with voltage.
- Logic gates (a few transistors each) combine bits: AND, OR, NOT, XOR.
- Boolean algebra and K-maps let designers use as few gates as possible.
- Adders (XOR, AND, OR) do arithmetic; multiplexers and decoders route and select.
- Latches and flip-flops (gates in a loop) remember bits; rows of them make registers.
- The clock keeps every register updating in step.
- The ALU, registers, control unit and PC together make a CPU, which runs instructions stored in memory.
- Machine code and assembly are those instructions; compilers and interpreters turn your Python into them.
Practice
- What's the difference between a combinational and a sequential circuit? Give an example of each.
Show the answer
A combinational circuit's output depends only on its current inputs; examples are an adder or a multiplexer. A sequential circuit also depends on what it stored before; examples are a latch, a flip-flop or a register.
- In the SR latch, what makes it remember?
Show the answer
The feedback loop: each NOR gate's output is an input to the other. When S and R are both 0, the outputs keep reinforcing each other, so Q stays as it was.
- Decode the instruction byte
88from the tiny CPU.
Show the answer
88 is 0101 1000: opcode 5 (JZ) and address 8. It means "if ACC is 0, jump to address 8".
print(88 >> 4, 88 & 0b1111)
5 8
- Change the tiny CPU's starting value from 5 to 10 (
memory[13] = 10). What total should it give, and how many instructions will it run?
Show the answer
Total = 10 + 9 + ... + 1 = 55. Each loop pass runs 8 instructions, 10 passes make 80, and the final LOAD, JZ and HALT add 3: 83 instructions.
- Which part of the CPU does each job: decides which circuits switch on for an instruction; holds the address of the next instruction; adds two numbers?
Show the answer
The control unit, the program counter, and the ALU.
Interview questions
What is the difference between a latch and a flip-flop?
A latch is level-sensitive: while its enable is active, its output follows the input. A flip-flop is edge-triggered: it captures the input only at a clock edge, usually the rising edge. Flip-flops let large synchronous circuits update in step.
Explain the fetch-decode-execute cycle.
The CPU fetches the instruction at the program counter's address from memory and increments the PC; decodes it in the control unit into an operation and operands; then executes it in the ALU or memory unit, writing results to registers or memory. Jump instructions change the PC instead.
What is the von Neumann architecture?
A design where instructions and data are stored in the same memory and travel over the same bus, with a CPU that fetches and executes instructions in sequence. Most general-purpose computers follow it, with caches to reduce the bottleneck of sharing one path to memory.
Key takeaways
- Feeding a gate's output back into its input creates memory: two NOR gates make a latch that stores one bit.
- Flip-flops update only on a clock tick; a register is a row of flip-flops; the clock keeps the whole CPU in step.
- A CPU is registers, a program counter, an ALU (adders, gates and a multiplexer) and a control unit (decoders).
- Instructions are numbers stored in memory; the CPU fetches, decodes and executes them, and jumps make loops.
- Every layer, from transistor to Python, is built from the one below and hides its details.
Frequently asked questions
How many transistors does a CPU need?
A very simple 8-bit CPU can be built with a few thousand. Modern desktop and laptop processors use billions, mostly for cache memory, many cores, and circuits that run several instructions at once.
Can I build a CPU myself?
Yes, as a learning project. Free simulators like Logisim Evolution let you build gates, adders, registers and a small CPU on screen. The free course "Nand to Tetris" builds a whole computer starting from NAND gates.
What does the clock speed actually measure?
How many clock ticks happen per second. Each tick lets the flip-flops capture new values. A modern core does several instructions per tick on average, so GHz alone doesn't tell you how fast a CPU is.
What to learn next
- Write instructions like these by hand in assembly language for beginners.
- Compare registers with RAM and SSDs in how RAM, hard disks and SSDs store data.
- Revise the CPU's parts in CPU, GPU, RAM and storage.