First PrinciplesStart anywhere. Prove it, then move on.

Rung 2

Loops and branches

Two shapes that let a short procedure do a long job.

Best attempted after 1. Instructions a machine could follow. Nothing stops you trying this now — the gate will tell you if you were right.

The gate

Hand-trace a procedure containing a loop nested inside another loop, writing down the value of every variable after each pass. Your written trace matches what the procedure actually produces, with no step skipped.

Nobody checks this but you. Do it honestly and the rungs above hold; do it loosely and they will not, somewhere further up where the cause is much harder to find.

A procedure written out flat can only be as long as your patience. Two shapes fix that. Repetition: do this again while something is true. Branching: do this if something is true, otherwise do that.

Almost every program ever written is these two shapes, nested, a few thousand times over.

Why this is on the ladder

Because a loop is where the machine stops being a list and starts being a process. It is also where your intuition first fails you — a loop with a condition that never becomes false runs forever, and a loop that runs one time too many or too few is the most common bug in the world. You cannot feel these errors. You have to trace them.

Tracing by hand is not a beginner's crutch you outgrow. It is what you will do at rung 45 when your network's loss does not go down.

Do this

Take this procedure. Do not run it on a computer — you have no computer on this rung.

total = 0
for row from 1 to 3:
    for column from 1 to 3:
        if row equals column:
            total = total + 10
        else:
            total = total + 1

Make a table with a line for every single pass of the inner loop — nine lines. Columns: row, column, which branch was taken, total afterwards. Fill in every cell. What is total at the end?

Then change 1 to 3 to 1 to 4 in both loops and do it again before you guess. Notice whether the answer changed the way you expected.

Where people get stuck

People skip lines in the trace once they think they see the pattern. That is precisely when the trace was about to earn its keep — the pattern you "see" is a guess, and the whole reason to trace is that guesses about loops are unreliable.

The other snag is the branch. if row equals column is true three times out of nine, not once. Off-by-one and how-many-times errors are the same error wearing different hats, and both are cured by writing the line down.

Reading