Counting

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

Every seventh visitor to a museum gets a free postcard. How many postcards does the museum give away when 50 visitors come?

int postcards = 0;
for (int visitor = 1; visitor <= 50; visitor++) {
    if (visitor % 7 == 0) {
        postcards++;
    }
}
printf("Postcards: %d\n", postcards);
Postcards: 7

The counter postcards starts at 0, before the loop. The loop goes through every visitor, and the if decides whether to count them: visitor % 7 == 0 is true when the remainder after dividing by 7 is 0. postcards++ runs only for the visitors 7, 14, 21, 28, 35, 42 and 49, so at the end, the counter is 7. Again, you print the result after the loop.

Notice the two pairs of curly braces: postcards++ is in the block of the if, which is in the block of the loop. If postcards++ ends up outside the if (but still in the loop), the program counts every visitor and prints Postcards: 50.

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

int postcards = 0;
int without = 0;
for (int visitor = 1; visitor <= 50; visitor++) {
    if (visitor % 7 == 0) {
        postcards++;
    } else {
        without++;
    }
}
printf("Postcards: %d\n", postcards);
printf("Without a postcard: %d\n", without);
Postcards: 7
Without a postcard: 43

7 + 43 is 50, one for each visitor. Adding up the counters like this is a quick way to check that you counted right.

Instructions

A street has houses numbered from 1 to HOUSES. The houses with odd numbers are on the left side of the street, the ones with even numbers on the right. Count the houses on the left side: create a variable left with the value 0, go through the numbers from 1 to HOUSES with a for loop, and for every odd number, increase left by 1. A number is odd when the remainder after dividing it by 2 is 1. After the loop, print the result as Left side: 13.

In the same loop, count the houses on the right side: before the loop, create a variable right with the value 0, and increase it in an else branch. After the loop, print Right side: 12 on the next line.

Start programming for free

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

Or sign up with:

6/11