20. Loop patterns — Homework solutions

The .lua solution files are in exercises/20/homework/solutions/.

Problem 1 — Factorial

Problem. Multiply 1 through 5 together.

How to think about it. Accumulate, but with * instead of +. Start the product at 1 — start at 0 and the answer is 0, since anything times zero is zero.

Worked solution.

local product = 1
for i = 1, 5 do
    product = product * i
end
print(product)     -- 120

Problem 2 — Count multiples

Problem. Count numbers from 1 to 50 that divide evenly by 7.

Worked solution.

local hits = 0
for i = 1, 50 do
    if i % 7 == 0 then
        hits = hits + 1
    end
end
print(hits)        -- 7   (7, 14, 21, 28, 35, 42, 49)

Problem 3 — First big square

Problem. Find the first number whose square is over 200.

Worked solution.

local first
for i = 1, 100 do
    if i * i > 200 then
        first = i
        break
    end
end
print(first)       -- 15   (14×14 = 196, 15×15 = 225)

Common mistakes.

  • Forgetting break, so the loop runs on and first lands on the last match, not the first.

Challenge — Range stats in one pass

Problem. Total, even-count, and a divisible-by-9 flag from one loop.

Worked solution.

local total = 0
local evens = 0
local has_nine = false

for i = 1, 20 do
    total = total + i
    if i % 2 == 0 then evens = evens + 1 end
    if i % 9 == 0 then has_nine = true end
end

print("total", total)        -- 210
print("evens", evens)        -- 10
print("divisible by 9", has_nine)  -- true   (9 and 18)

Common mistakes.

  • Writing three separate loops over the same range. One pass does all three jobs — that is why you learn to spot the patterns.

Done?

That ends Part 4. You can branch with if, reason about truth with and/or/not, repeat with every kind of loop, nest loops for grids, and pick the right loop pattern on sight. Part 4 has two mini-projects to tie it together: the Number Guessing Game and Rock-Paper-Scissors.