Sum and Average
Now that you can go through a list, let's look at what such loops are used for most often. The first pattern adds up all the items. You know it from the lesson on loops: a variable that starts at 0 before the loop and grows in each iteration. Here's how much milk, in liters, Bella the cow gave over four days:
local milk = {12, 15, 11, 14}
local total = 0
for _, liters in ipairs(milk) do
total = total + liters
end
print("Total: " .. total .. " liters")This prints:
Total: 52 literstotal starts at 0, because before you add anything, the sum is zero. In each iteration, the loop adds one item: after the first iteration, total is 12, then 27, 38, and finally 52. The print comes after the loop, when the sum is complete. Inside the loop, it would print every partial sum.
The average is the sum divided by the number of items, which is #milk:
local milk = {12, 15, 11, 14}
local total = 0
for _, liters in ipairs(milk) do
total = total + liters
end
local average = total / #milk
print("Average: " .. average)This prints:
Average: 13.0Remember from the lesson on variables that / always gives a decimal number, even when the result is whole, so 52 / 4 is 13.0. And when the result isn't whole, you can get a lot of digits. For the milk of a whole week, {12, 15, 11, 14, 13, 16, 9}, the average is 90 / 7, which prints as 12.857142857143. To round it for printing, use string.format with %.1f, one decimal place:
print(string.format("Average: %.1f liters", 90 / 7))This prints:
Average: 12.9 litersDon't use // for an average: it rounds down to a whole number, and 90 // 7 is just 12.
Watch out for an empty list. Its sum is 0 and its length is 0, so the average would be 0 / 0, which isn't a number at all. Lua doesn't stop the program: it calculates a special value, nan (not a number), and on this site, print(0 / 0) prints -nan. If a list can be empty, check #milk > 0 before dividing.
The sum and the average often lead to more questions, for example which days were above average. To answer that, you need the average first, so you go through the list a second time, after the first loop has finished.
Instructions
Add up the milk: create a local variable total with the value 0, go through milk in a loop, and add each item to total. After the loop, print Total: 90 liters.
Calculate the average from total and #milk, and print it with one decimal place, using string.format: Average: 12.9 liters.
Count the days when Bella gave more milk than the average. Go through milk again, compare each item with the average (not the rounded one), and after the loop, print Above average: 4 days.
Start programming for free
8/11