Back

Debug Challenge: Loops

divider

Objective

Four short programs with loops in them, each with exactly one thing wrong. One of them will not stop.

Read before you run. A program with a loop that never ends gives you a window that ignores you. If you do run it and it hangs, close the terminal panel and reopen it.

The Four Programs


Bug 1

This should add five numbers and print Total: 61. It stops with an error about a nil value instead.

Bug 1
local scores = {12, 8, 21, 3, 17}
for i = 1, #scores do
local total = 0
total = total + scores[i]
end
print("Total: " .. total)

There are two things wrong here and they have the same cause. Find the cause and both go away.


Bug 2

Three names in the table, and it prints two of them.

Bug 2
local names = {"Ada", "Bo", "Cy"}
for i = 1, #names - 1 do
print(names[i])
end

Bug 3

This should count down from 3 and then say Game over. It prints Life 3 forever.

Bug 3
local lives = 3
while lives > 0 do
print("Life " .. lives)
end
print("Game over")

Bug 4

This should keep going until x drops to 10, taking about ten passes. It takes one.

Bug 4
local x = 20
local passes = 0
repeat
passes = passes + 1
x = x - 1
until x > 10
print("Passes: " .. passes)

The loop itself is fine. Read the word before the condition.


Submit

For each program, give:

  • One sentence on what was wrong
  • The corrected line of code
  • For bug 3 only: the general rule that would have caught it before you ran anything

Count the passes on paper. For each loop, write down what the condition is at the start of every pass. Four rows is usually enough to see the problem.

Worth 5 points, graded on completion.

Commence Debugging