← CS Unplugged

CS Unplugged activity

Little Man Computer: branches and loops

About 20 minutesSoloPencil

On the tracing sheet, the little man always worked straight down the list, one line after the next. Real programs loop and make decisions instead, and that only takes one new trick: an instruction that changes the program counter to something other than “the next line.” That’s a branch.

CodeMnemonicWhat it does
6xxBRAJump there. Always.
7xxBRZJump there, but only if the accumulator is exactly zero.
8xxBRPJump there, but only if the accumulator is zero or positive.

A loop is just a BRA that jumps backward, to an instruction the little man already ran. BRZ and BRP are how he decides whether to keep looping or to fall through, by checking the accumulator first.

Worked example

This program takes one number and counts down to 1, outputting each number along the way, then stops as soon as the accumulator hits zero. Watch how the program counter jumps back to address 01 instead of just moving to the next line.

Now you trace it

Same routine as the tracing sheet: start at address 00, follow the program counter, and fill in every row in order. This time the program counter won’t just count up by one every row, so read the Instruction column carefully each step, especially right after a branch.

CC BY-NC-SA 4.0.