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: 3The 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: 4The 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
- 1
The vector
scoresholds the points from a test. You pass with 50 points or more. Count the students who passed: create a variablepassedwith the value0, go throughscoreswith a loop, and for every score of at least 50, increasepassedby 1. After the loop, print the result asPassed: 5. - 2
In the same loop, count the students who failed: before the loop, create a variable
failedwith the value0, and increase it in anelsebranch. After the loop, printFailed: 3on the next line.