19. Nested loops — Homework solutions
The .lua solution files are in
exercises/19/homework/solutions/.
Problem 1 — Rectangle of hashes
Problem. A 5-wide, 3-tall block of
#.
How to think about it. Outer loop = rows (3). Inner
loop = columns (5): build a row of five #, then print
it.
Worked solution.
for row = 1, 3 do
local line = ""
for col = 1, 5 do
line = line .. "#"
end
print(line)
endProblem 2 — Coordinate pairs
Problem. Print every (x, y) for x and y
from 1 to 3.
Worked solution.
for x = 1, 3 do
for y = 1, 3 do
print("(" .. x .. ", " .. y .. ")")
end
endOutput: (1, 1), (1, 2),
(1, 3), (2, 1), ... — nine lines.
Common mistakes.
- Reusing
xfor both loops. Each loop needs its own.
Problem 3 — Times table
Problem. A 5×5 multiplication grid.
Worked solution.
for row = 1, 5 do
local line = ""
for col = 1, 5 do
line = line .. (row * col) .. "\t"
end
print(line)
endOutput:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Challenge — Right triangle
Problem. A 6-row triangle where row n
has n stars, then upside down.
Worked solution.
-- growing
for row = 1, 6 do
local line = ""
for star = 1, row do
line = line .. "*"
end
print(line)
end
-- shrinking
for row = 6, 1, -1 do
local line = ""
for star = 1, row do
line = line .. "*"
end
print(line)
endThe two differ only in the outer loop's direction: 1, 6
up, 6, 1, -1 down. The inner loop is identical.
Common mistakes.
- Looping the inner range
1, 6(fixed) instead of1, row. A fixed inner range gives a rectangle; the triangle comes from tying the inner count to the current row.
Done?
You can build grids and shapes from loops inside loops. The last chapter of Part 4 — Loop patterns — names the jobs loops do most: adding up, counting, searching, and flagging.