18. Loops — Homework solutions
The .lua solution files are in
exercises/18/homework/solutions/.
Problem 1 — Count to 20
Problem. Print 1 through 20 with a
while loop.
How to think about it. A while loop
needs a start value, a stop condition, and an update. Start at 1, stop
past 20, add 1 each pass.
Worked solution.
local i = 1
while i <= 20 do
print(i)
i = i + 1
endCommon mistakes.
- Forgetting
i = i + 1. The condition stays true forever, so the loop never ends. - Using
i < 20, then missing 20.<=includes the endpoint.
Problem 2 — Multiplication table of 7
Problem. Print 7 * i = result for
i from 1 to 12.
How to think about it. The classic numeric
for. Each pass prints a line from i and
7 * i.
Worked solution.
for i = 1, 12 do
print("7 * " .. i .. " = " .. (7 * i))
endThe parentheses around 7 * i are not required
(multiplication binds tighter than ..) but clarify
intent.
Common mistakes.
- Writing
for i = 1, 12, 1 do. The step argument defaults to1, so it is just noise. Leave it out. - Confusing
7 * i(printed) withi(the counter).
Problem 3 — Stop at the threshold
Problem. Add 1, 2, 3, ... to a total. Stop once it exceeds 100. Print the counter and the total.
How to think about it. Two variables: a counter that
grows by 1 each pass, and a total that grows by the counter. The exit,
total > 100, fits inside as if ... break,
which suits while true do.
Worked solution.
local i = 1
local total = 0
while true do
total = total + i
if total > 100 then
break
end
i = i + 1
end
print("Stopped at i = " .. i .. " with total = " .. total)For i = 1..14, the sum 1+2+...+14 = 105 is
the first total over 100:
Stopped at i = 14 with total = 105
Common mistakes.
- Adding
i = i + 1before adding tototal. That adds the nexti, not the current. Order them on purpose. - Putting the
breakafteri = i + 1. Then the printediis one past the value that pushed the total over 100. Either works; be deliberate.
Challenge — Sum 1..N
Problem. Read n, sum 1..n with a
for loop, compare with the closed form
n * (n + 1) / 2.
How to think about it. A for loop from
1 to n adds each counter to a total. The closed form for
the first n positive integers is
n * (n + 1) / 2, Gauss's trick. Print both, confirm they
match.
Worked solution.
io.write("Enter a positive whole number n: ")
local n = tonumber(io.read())
local total = 0
for i = 1, n do
total = total + i
end
print("Sum from 1 to " .. n .. " is " .. total)
print("Formula gives " .. (n * (n + 1) / 2))The / operator gives a float, so the second line shows a
trailing .0. Expected.
Common mistakes.
- Forgetting to set
totalto0before the loop. Anilstart meansnil + 1, an error. - Writing the formula as
n * n + 1 / 2. Order of operations matters: the parentheses around(n + 1)are needed.
Done?
You can now repeat work with every kind of loop. Next, Nested loops nests loops to build grids, and Loop patterns names the jobs loops do most. Then Part 4's mini-projects — a Number Guessing Game and Rock-Paper-Scissors — combine decisions and repetition.