Adding Up in a Loop
Loops can do more than print. Very often, they add up many values. Emma's strawberries are ripening: on day 1 she picks 1 basket, on day 2 two baskets, on day 3 three, and so on. How many baskets does she pick in 10 days?
local total = 0
for day = 1, 10 do
total = total + day
end
print("Baskets: " .. total)Baskets: 55The variable total collects the sum. It starts at 0, because before you add anything, the sum is zero. In each iteration, total = total + day adds one day's baskets. To watch the sum grow, you can print it inside the loop for a moment:
local total = 0
for day = 1, 5 do
total = total + day
print(total)
end1
3
6
10
15After day 1, the sum is 1, after day 2 it's 3 (1 + 2), then 6 (1 + 2 + 3), and so on. Printing values inside a loop like this is the simplest way to find out what a loop really does when its result surprises you.
Where each line goes matters:
local total = 0goes before the loop, so that it runs only once. Inside the loop's block, it would create a newtotalwith the value 0 in every iteration. And after the loop, thattotalwouldn't exist: a local variable created in a block exists only in that block, just like the variable of aforloop. The program would end withattempt to concatenate a nil value (global 'total').printgoes after the loop, when the sum is complete. Inside the loop, it prints every partial sum, as above.
The average is the sum divided by the number of values. Remember that / always gives a decimal number:
local total = 0
for day = 1, 10 do
total = total + day
end
print("Average: " .. total / 10)Average: 5.5The calculation total / 10 happens before the joining with .., so you don't need parentheses. If the sum were 60, you would get 6.0. To always print one decimal place, use string.format("%.1f", total / 10).
Instructions
How many strawberries does Emma pick in these six days? Before the loop, create a local variable total with the value 0. In the loop, add the day's strawberries, day * 3, to it. After the loop, print the sum:
Total: 63At the end of the program, print the average number of strawberries per day: total divided by 6:
Average: 10.5Start programming for free
5/10