Teach & case

Help a near-peer reason through the idea — when you explain it, you understand it best — then read the real decision it comes from.

A case · you decide

Lin's crash on line 42

Lin — a student whose program crashes with an error pointing at line 42

The idea in play: tracing state line-by-line to find a bug — not guessing from where the error surfaced.

Lin's program crashes: "TypeError on line 42 — cannot read length of undefined." Line 42 looks fine. Her instinct is to start rewriting line 42 until the red goes away.

The crash SURFACED on line 42, but that's where the bad value was USED — not where it was created. The variable became undefined somewhere earlier and rode along until line 42 tried to use it.

Lin adds a print (or a breakpoint) at each step and watches the variable's actual value change line by line. On line 27 it's a list; on line 31 a function returned nothing and overwrote it with undefined. THAT's the bug — 15 lines above the crash.

The error points at line 42. Where's the actual bug most likely to be?

Lin's friend says "just add a try/catch around line 42 so it stops crashing." Good fix?

Trace a bug yourself in the Debugger →

When two ideas meet: 2 cases with two people

A case · you decide

Devi and Lin: the loop that stops one short

Devi & Lin — a student who writes loops, and a friend who traces them line by line

The idea in play: tracing a loop by hand shows exactly which values it visits, which is how off-by-one bugs are found.

Devi's function should add the numbers 1 to n. For n = 5 it should return 15, but it returns 10.

The loop is: total = 0; for i from 1 while i < n: total = total + i.

Lin traces it for n = 5: i is 1, 2, 3 and 4. Then i becomes 5, and 5 < 5 is false.

What is the fix?

Open the Trace Lab →

A case · you decide

Odile and Milo: a function that calls itself

Odile & Milo — a student who writes recursion, and a friend who thinks in functions

The idea in play: a recursive function needs a base case that stops it, and each call must move closer to that base case.

Odile writes factorial(n) = n × factorial(n − 1). Milo runs factorial(4) and the program never finishes.

factorial(4) calls factorial(3), then 2, 1, 0, −1, −2, and keeps going.

What does the function need?

Open the Trace Lab →