Counting
The second pattern counts: how many elements meet a condition? It looks like adding up, but instead of the element, you add 1, and only when an if says so. This program counts the hot days of one week:
int temperatures[] = {18, 24, 27, 15, 31, 22, 29};
int count = sizeof(temperatures) / sizeof(temperatures[0]);
int hot_days = 0;
for (int i = 0; i < count; i++) {
if (temperatures[i] >= 25) {
hot_days++;
}
}
printf("Hot days: %d\n", hot_days);This prints:
Hot days: 3The counter hot_days starts at 0, before the loop. The loop looks at every temperature, and the if decides whether to count it. hot_days++ runs only for 27, 31 and 29, so at the end, the counter is 3. Notice the two pairs of curly braces: hot_days++ is in the block of the if, which is in the block of the loop. Again, you print the result after the loop.
Don't mix up the two numbers. count is the number of all the elements, 7, and the loop needs it to go through all of them. hot_days is the number of elements that meet the condition, and that's the result.
The condition can check anything about the element. This loop counts how many times a die rolled a six:
int rolls[] = {6, 2, 6, 4, 1, 6, 3};
int count = sizeof(rolls) / sizeof(rolls[0]);
int sixes = 0;
for (int i = 0; i < count; i++) {
if (rolls[i] == 6) {
sixes++;
}
}
printf("Sixes: %d\n", sixes);This prints:
Sixes: 3One 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 array 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
8/12