Counting

The second pattern counts: how many days, plots or eggs meet a condition? It looks like adding up, but instead of a value, you add 1, and only when an if says so.

Hugo the trader comes to the farm every 5th day. How many times does he come in 30 days?

local visits = 0
for day = 1, 30 do
    if day % 5 == 0 then
        visits = visits + 1
    end
end
print("Hugo's visits: " .. visits)
Hugo's visits: 6

The counter visits starts at 0, before the loop. The loop goes through every day, and the if decides whether to count it. You know % from the lesson on variables: it gives the remainder after division. day % 5 == 0 is true when the day can be divided by 5 with nothing left over, which is every 5th day: 5, 10, 15, 20, 25 and 30. With % 7, you'd get every 7th day, and with % 2 every other day (the even ones). Again, you print the result after the loop.

Notice the two ends: the first one closes the if, the second one the loop. With 4 more spaces of indentation for each level, you can see which end belongs to what. If visits = visits + 1 ends up outside the if (but still in the loop), the program counts every day and prints Hugo's visits: 30.

One loop can count several things, each in its own counter. With if and else, every day is counted exactly once, in one counter or the other:

local visits = 0
local quiet = 0
for day = 1, 30 do
    if day % 5 == 0 then
        visits = visits + 1
    else
        quiet = quiet + 1
    end
end
print("Days with Hugo: " .. visits)
print("Days without Hugo: " .. quiet)
Days with Hugo: 6
Days without Hugo: 24

6 + 24 is 30, one for each day. Adding up the counters like this is a quick way to check that you counted right.

Instructions

This season, it rains every 3rd day: on day 3, 6, 9 and so on. Count the rainy days: create a local variable rainy with the value 0, go through the days from 1 to days with a for loop, and for every day that can be divided by 3, increase rainy by 1. After the loop, print:

Rainy days: 13

On all the other days, Emma has to water. Count them in the same loop: before the loop, create a local variable dry with the value 0, and increase it in an else branch. After the loop, print the result on the line below the rainy days:

Rainy days: 13
Dry days: 27

Emma goes to the market every 7th day, but not when it rains. In the same loop, count the days that can be divided by 7 and not by 3 in a third counter, market. At the end, print:

Market days: 4

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/10