Branching and Loops
A program that only goes forward is boring. Real programs make decisions: "if the button is pressed, turn on the LED," or "repeat this operation 10 times." How does a processor branch and loop?
The secret is conditional jumps. The processor has a special register — the status flags. After each ALU operation, the flags are updated: was the result zero? Was it negative? Did a carry occur? Then the program can use conditional jump instructions: JZ (jump if zero), JNZ (jump if not zero), JC (jump if carry).
A loop is simply a conditional jump backward. The program counter normally increments: after executing instruction N, it moves to N+1. But a JMP (unconditional jump) or a conditional jump instruction can change the program counter to any address. If you jump backward to re-execute already-run instructions — you've created a loop.
Practical example. Let's write a program that counts from 5 down to 0. Assembly pseudocode: load 5 into the accumulator; label LOOP; decrement accumulator; if not zero, jump to LOOP; HALT. Each iteration, the ALU subtracts 1, updates the zero flag, and the conditional jump either sends the PC back to LOOP (if the result is not zero) or lets it fall through to the HALT instruction.