04. Tracing a program by hand — Homework solutions

These are paper problems, so the "solution" is the finished trace and output. Compare your table to this one. A wrong output is almost always one row with the new value in the wrong column, or a skipped loop round.

Problem 1 — Sum of a countdown

Problem. Trace the down-counting loop and give the printed value.

How to think about it. i starts at 5 and drops by 1 each round down to 1, adding the current i to s.

Worked trace.

Round (i) s before s after
5 0 5
4 5 9
3 9 12
2 12 14
1 14 15

Output: 15. (It is just 5 + 4 + 3 + 2 + 1.)

Problem 2 — Building a string

Problem. Trace the string being glued together three times.

How to think about it. out starts empty (""). Each round sticks "ha" onto the end of what out holds.

Worked trace.

Round (i) out before out after
1 "" ha
2 ha haha
3 haha hahaha

Output: hahaha.

Common mistake. Writing ha ha ha with spaces. The program has none — .. glues the pieces with nothing between.

Problem 3 — The swap

Problem. Trace the three-line swap and give the final output.

How to think about it. temp holds a copy of a so its old value is not lost when a is overwritten next.

Worked trace.

Line a b temp
local a = 2 2
local b = 7 2 7
local temp = a 2 7 2
a = b 7 7 2
b = temp 7 2 2

Output: 7 2 (the two values printed with a tab between them).

What temp does. It is a holding spot. Without it, a = b overwrites a before the old a reaches b, so both end up as 7.

Challenge — Spot the surprise

Problem. Trace the discount program.

How to think about it. final is worked out on its own line, using the value discount had at that moment (20). Changing discount later does not redo final.

Worked trace.

Line price discount final
local price = 100 100
local discount = 20 100 20
local final = price - discount 100 20 80
discount = 50 100 50 80

Output: 80.

Why. final was set once, while discount was 20, so it became 80 and stayed there. discount = 50 changes only discount. A variable does not remember the formula that made it, only its value. Same trap as the worked example at the top of the chapter, new costume.

Done?

You can now read a program and say what it will do before running it. The next chapter — Naming and decomposition — covers the other half of reading well: clear names, and chopping a big job into small ones, so the trace is easy from the start.