Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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.

  2. 2

    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.

Back

7/13

  1. 1. The while Loop
  2. 2. Infinite Loops
  3. 3. The for Loop
  4. 4. Looping over a Vector
  5. 5. Loops and Text
  6. 6. Sum and Average
  7. 7. Counting
  8. 8. The Largest Value
  9. 9. Building a New Vector
  10. 10. The break Statement
  11. 11. The continue Statement
  12. 12. Nested Loops
  13. 13. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.