Algorithms
Count Matches
A counting loop increments a result when an element satisfies a condition.
predicate
The condition decides whether one element contributes to the count.
counter
The counter changes only when the condition is true.
Count Matches
count_matches.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int threshold = 5;
int values[5] = {2, 5, 7, 9, 4};
int count = 0;
for (int i = 0; i < 5; i++) {
if (values[i] >= threshold) {
count++;
}
}
printf("count=%d\n", count);
return 0;
}
#include <stdio.h>
int main(void) {
int threshold = 3;
int values[5] = {2, 5, 7, 9, 4};
int count = 0;
for (int i = 0; i < 5; i++) {
if (values[i] >= threshold) {
count++;
}
}
printf("count=%d\n", count);
return 0;
}
#include <stdio.h>
int main(void) {
int threshold = 8;
int values[5] = {2, 5, 7, 9, 4};
int count = 0;
for (int i = 0; i < 5; i++) {
if (values[i] >= threshold) {
count++;
}
}
printf("count=%d\n", count);
return 0;
}
threshold ← 5, values ← ⟨addr A⟩, count ← 0
3int main(void) {4 int threshold→ 5 = 5; //@threshold=3, 85 int values→ ⟨addr A⟩[5] = {2, 5, 7, 9, 4};6 int count→ 0 = 0;for (int i = 0; i < 5; i++)
pass 1 of 58for (int i0 = 0; i < 5; i++) {9 if (values[i] >= threshold) {All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 count ← 1
pass 1 of 38for (int i = 0; i < 5; i++) {9 if (values[i]5 >= threshold5) {10 count→ 1++;11 }All 3 passes — pass 1 is the card above pass values[i]count1 5 0 → 1 2 7 1 → 2 3 9 2 → 3 printf("count=%d ", count);
14 printf("count=%d\n", count3);15 return 0;16}outputcount=3
threshold ← 3, values ← ⟨addr A⟩, count ← 0
3int main(void) {4 int threshold→ 3 = 3;5 int values→ ⟨addr A⟩[5] = {2, 5, 7, 9, 4};6 int count→ 0 = 0;for (int i = 0; i < 5; i++)
pass 1 of 58for (int i0 = 0; i < 5; i++) {9 if (values[i] >= threshold) {All 5 passes — pass 1 is the card above pass i1 0 2 1 3 2 4 3 5 4 count ← 1
pass 1 of 48for (int i = 0; i < 5; i++) {9 if (values[i]5 >= threshold3) {10 count→ 1++;11 }All 4 passes — pass 1 is the card above pass values[i]count1 5 0 → 1 2 7 1 → 2 3 9 2 → 3 4 4 3 → 4 printf("count=%d ", count);
14 printf("count=%d\n", count4);15 return 0;16}outputcount=4
threshold ← 8, values ← ⟨addr A⟩, count ← 0
3int main(void) {4 int threshold→ 8 = 8;5 int values→ ⟨addr A⟩[5] = {2, 5, 7, 9, 4};6 int count→ 0 = 0;for (int i = 0; i < 5; i++)
pass 1 of 58for (int i0 = 0; i < 5; i++) {9 if (values[i] >= threshold) {All 5 passes — pass 1 is the card above pass ivalues[i]thresholdcount1 0 — — — 2 1 — — — 3 2 — — — 4 3 9 8 0 → 1 5 4 — — — count ← 1
8for (int i = 0; i < 5; i++) {9 if (values[i]9 >= threshold8) {10 count→ 1++;11 }printf("count=%d ", count);
14 printf("count=%d\n", count1);15 return 0;16}outputcount=1