Back

Debug Challenge: Values and Arithmetic

divider

Objective

Four short programs, each with exactly one thing wrong. Every one of them runs to the end without an error and gives an answer that is not the answer.

Three kinds of mistake show up in Lua. A syntax error stops the program before it starts, and nothing at all is printed. A runtime error prints some output and then stops — that partial output is how you tell the two apart. A logic error runs cleanly to the end and is wrong, which is the one that costs marks.

All four of these are logic errors. If you find yourself waiting for an error message, that is the habit this challenge exists to break.


The Four Programs


Bug 1

The person types 7. It charges them correctly and then never says Lucky number.

Bug 1
io.write("How many tickets? ")
local n = io.read()
print("That will be " .. n * 12 .. " dollars.")
if n == 7 then
print("Lucky number.")
end

Bug 2

This should print Total: 8. It prints Total: 53.

Bug 2
local a = 5
local b = 3
print("Total: " .. a .. b)

Bug 3

17 items, 5 to a box. This should say 3 full boxes. It says 2.

Bug 3
local total = 17
local perBox = 5
print("Full boxes: " .. total % perBox)

Bug 4

Two items at $4.50 plus $3 shipping should be Two of them: 12. It says Two of them: 10.5.

Bug 4
local price = 4.50
local shipping = 3
print("Two of them: " .. price + shipping * 2)

Submit

For each program, give:

  • One sentence on what was wrong
  • The corrected line of code
  • For bug 1 only: why there was no error message

Read them first. Running the code tells you that something is wrong; it rarely tells you why, and in May there is no computer.

Worth 5 points, graded on completion.

Commence Debugging