Counting

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

std::vector<int> temperatures = {18, 24, 27, 15, 31, 22, 29};
int hotDays = 0;
for (int temperature : temperatures) {
    if (temperature >= 25) {
        hotDays++;
    }
}
std::cout << "Hot days: " << hotDays << std::endl;
Hot days: 3

The counter hotDays starts at 0, before the loop. The loop looks at every temperature, and the if decides whether to count it. hotDays++ runs only for 27, 31 and 29, so at the end, the counter is 3. Notice the two pairs of curly braces: hotDays++ is in the block of the if, which is in the block of the loop. Again, you print the result after the loop.

Counting works with text too. This loop counts the lowercase letters a:

std::string word = "Abracadabra";
int count = 0;
for (char character : word) {
    if (character == 'a') {
        count++;
    }
}
std::cout << "Number of a: " << count << std::endl;
Number of a: 4

The uppercase A at the start isn't counted: 'A' and 'a' are different characters.

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

Instructions

The vector scores holds the points from a test. You pass with 50 points or more. Count the students who passed: create a variable passed with the value 0, go through scores with a loop, and for every score of at least 50, increase passed by 1. After the loop, print the result as Passed: 5.

In the same loop, count the students who failed: before the loop, create a variable failed with the value 0, and increase it in an else branch. After the loop, print Failed: 3 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:

7/13