How does a CPU work
The ALU does the calculating, and instructions decide what to do. How do the two move as one? Follow the flow of a CPU handling instructions one at a time and you'll find the answer.
The CPU repeats three beats
What a CPU does is actually simple.
It fetches one instruction, works out what that instruction means, and carries it out.
Then it fetches the next instruction.
It repeats these three beats without stopping.
Fetch → decode → execute, and repeat.
If fetch, decode, and execute make one round, a CPU runs billions of these rounds every 1 second.
Each step is simple, but they're so fast that together they get complex work done.
A finger pointing at the next instruction
But how does the CPU know which instruction it's up to?
The instructions sit in a row somewhere in memory, and one device points at "the next one to do."
It's called the PC, the program counter.
The PC points at the next instruction.
Every time an instruction is fetched, the PC moves up by one.
After instruction 0 comes 1, after 1 comes 2, and so on.
Thanks to this finger, the CPU never loses its place and works through the instructions in order.
The parts come together into a CPU
Now the parts come together.
The PC that points to the next instruction, the decoder that works out instructions, the ALU that calculates, and the registers, small cells that hold values for a moment.
Each is small on its own, but together they make one CPU that processes instructions.
The CPU as one body.
The PC points to what's next, the decoder works out the instruction, the ALU calculates, and the registers hold values.
Each doing its own job while turning the same beat together: that's how a CPU works.
Run three lines of instructions
Here's a short program.
It has three lines: "load 3," "add 4," and "show the result."
Each time you press step, it moves one beat forward, and you can watch the PC move and the value build up.
Run one line at a time, following the PC.
As the PC went up through 0, 1, and 2, the instructions ran one by one.
The value became 3, then 7, and finally appeared on the screen.
That's what it looks like when a program runs.
When the PC jumps somewhere else
The PC usually moves forward one step at a time, but sometimes it jumps elsewhere.
When it meets an instruction like "go to instruction 5," the PC changes to that address.
When this jump meets the true or false from a comparison in the last lesson, it becomes a fork in the road called "if."
The PC jumps from 2 to 5.
Change the PC to a different value instead of stepping by one, and the flow of the program changes.
It can skip ahead or go back.
How these jumps become "if" and "repeat" is covered in detail in the programming section.